Skip to content

Commit 422a50f

Browse files
committed
feature/cache: Add cache set feature
1 parent 50ea2bc commit 422a50f

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/cache.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
11
const hash = require('object-hash');
22

3-
function cache(func) {
3+
function cache(func, options) {
44
return (root, args, context) => {
55
if (!context.resolverCache) {
66
throw new Error('Missing resolverCache property on the Graphql context.');
77
}
88

99
const key = `${hash(root)}:${hash(args)}`;
10+
const executeAndCache = () =>
11+
Promise.resolve(func(root, args, context)).then(value =>
12+
context.resolverCache.set(key, value, options)
13+
);
14+
1015
return (
1116
context.resolverCache
1217
.get(key)
13-
.then(result => (result ? result : func(root, args, context)))
18+
.then(value => (value ? value : executeAndCache()))
1419
// Error
15-
.catch(() => func(root, args, context))
20+
.catch(() => executeAndCache())
1621
);
1722
};
1823
}

0 commit comments

Comments
 (0)