-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathrequestCache.js
More file actions
75 lines (62 loc) · 2.19 KB
/
requestCache.js
File metadata and controls
75 lines (62 loc) · 2.19 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
'use strict';
const { createHash } = require('crypto');
const { AsyncLocalStorage } = require('async_hooks');
const REQUEST_CACHE_STORAGE_KEY = Symbol.for('sd.requestCacheStorage');
/**
* Get the request-local cache storage instance.
* @returns {AsyncLocalStorage<Map<string, Promise<*>>>} Async local storage for request cache entries
*/
function getRequestCacheStorage() {
if (!global[REQUEST_CACHE_STORAGE_KEY]) {
global[REQUEST_CACHE_STORAGE_KEY] = new AsyncLocalStorage();
}
return global[REQUEST_CACHE_STORAGE_KEY];
}
/**
* Build a cache key for the given scope and params.
* @param {String} scope Cache scope name
* @param {Object} params Parameters contributing to the cache key
* @returns {String} Hashed cache key
*/
function getRequestCacheKey(scope, params) {
return createHash('sha256').update(JSON.stringify({ scope, params })).digest('hex');
}
/**
* Resolve a value using the current request-local cache when available.
* @param {Object} config Cache configuration
* @param {String} config.scope Cache scope name
* @param {Object} config.params Parameters contributing to the cache key
* @param {Function} config.fetcher Function that resolves the uncached value
* @param {Function} [config.shouldCache] Predicate deciding whether to keep the resolved value cached
* @returns {Promise<*>} Cached or newly fetched result
*/
function cacheBy({ scope, params, fetcher, shouldCache }) {
const requestCache = getRequestCacheStorage().getStore() || null;
if (!requestCache) {
return fetcher();
}
const cacheKey = getRequestCacheKey(scope, params);
if (requestCache.has(cacheKey)) {
return requestCache.get(cacheKey);
}
requestCache.set(
cacheKey,
Promise.resolve()
.then(fetcher)
.then(result => {
if (shouldCache && !shouldCache(result)) {
requestCache.delete(cacheKey);
}
return result;
})
.catch(err => {
requestCache.delete(cacheKey);
throw err;
})
);
return requestCache.get(cacheKey);
}
module.exports = {
cacheBy,
getRequestCacheStorage
};