Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { ObjectCacheAction, ObjectCacheActionTypes, AddToObjectCacheAction, RemoveFromObjectCacheAction } from "./object-cache.actions";
import { hasValue } from "../../shared/empty.util";
export interface CacheableObject {
uuid: string;
}
export interface ObjectCacheEntry {
data: CacheableObject;
timeAdded: number;
msToLive: number;
}
export interface ObjectCacheState {
[uuid: string]: ObjectCacheEntry
}
// Object.create(null) ensures the object has no default js properties (e.g. `__proto__`)
const initialState: ObjectCacheState = Object.create(null);
export const objectCacheReducer = (state = initialState, action: ObjectCacheAction): ObjectCacheState => {
switch (action.type) {
case ObjectCacheActionTypes.ADD: {
return addToObjectCache(state, <AddToObjectCacheAction>action);
}
case ObjectCacheActionTypes.REMOVE: {
return removeFromObjectCache(state, <RemoveFromObjectCacheAction>action)
}
default: {
return state;
}
}
};
function addToObjectCache(state: ObjectCacheState, action: AddToObjectCacheAction): ObjectCacheState {
return Object.assign({}, state, {
[action.payload.objectToCache.uuid]: {
data: action.payload.objectToCache,
timeAdded: new Date().getTime(),
msToLive: action.payload.msToLive
}
});
}
function removeFromObjectCache(state: ObjectCacheState, action: RemoveFromObjectCacheAction): ObjectCacheState {
if (hasValue(state[action.payload])) {
let newObjectCache = Object.assign({}, state);
delete newObjectCache[action.payload];
return newObjectCache;
}
else {
return state;
}
}