-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathcache.js
executable file
·63 lines (49 loc) · 1.65 KB
/
cache.js
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
59
60
61
62
63
const getItems = require('./get-items');
const defaultMakeCacheKey = key => key;
module.exports = function (cacheMap, keyFieldName, options = {}) {
const clone = options.clone || defaultClone;
const makeCacheKey = options.makeCacheKey || defaultMakeCacheKey;
return context => {
keyFieldName = keyFieldName || (context.service || {}).id; // Will be undefined on client
let items = getItems(context);
items = Array.isArray(items) ? items : [items];
if (context.type === 'after') {
if (context.method === 'remove') return;
const $select = (context.params.query || {}).$select;
if (context.method === 'find' && $select) return;
items.forEach(item => {
const idName = getIdName(keyFieldName, item);
const key = makeCacheKey(item[idName]);
cacheMap.set(key, clone(item));
});
return;
}
switch (context.method) {
case 'find': // fall through
case 'create':
return;
case 'get': {
const key = makeCacheKey(context.id);
const value = cacheMap.get(key);
if (value) context.result = value;
return context;
} default: // update, patch, remove
if (context.id) {
cacheMap.delete(context.id);
return;
}
items.forEach(item => {
const idName = getIdName(keyFieldName, item);
const key = makeCacheKey(item[idName]);
cacheMap.delete(key);
});
}
};
};
function getIdName (keyFieldName, item) {
if (keyFieldName) return keyFieldName;
return ('_id' in item) ? '_id' : 'id';
}
function defaultClone (obj) {
return JSON.parse(JSON.stringify(obj));
}