1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 |
|
7 | function getCacheId(request, withContext) {
|
8 | return JSON.stringify({
|
9 | context: withContext ? request.context : "",
|
10 | path: request.path,
|
11 | query: request.query,
|
12 | request: request.request
|
13 | });
|
14 | }
|
15 |
|
16 | module.exports = class UnsafeCachePlugin {
|
17 | constructor(source, filterPredicate, cache, withContext, target) {
|
18 | this.source = source;
|
19 | this.filterPredicate = filterPredicate;
|
20 | this.withContext = withContext;
|
21 | this.cache = cache || {};
|
22 | this.target = target;
|
23 | }
|
24 |
|
25 | apply(resolver) {
|
26 | const target = resolver.ensureHook(this.target);
|
27 | resolver.getHook(this.source).tapAsync("UnsafeCachePlugin", (request, resolveContext, callback) => {
|
28 | if(!this.filterPredicate(request)) return callback();
|
29 | const cacheId = getCacheId(request, this.withContext);
|
30 | const cacheEntry = this.cache[cacheId];
|
31 | if(cacheEntry) {
|
32 | return callback(null, cacheEntry);
|
33 | }
|
34 | resolver.doResolve(target, request, null, resolveContext, (err, result) => {
|
35 | if(err) return callback(err);
|
36 | if(result) return callback(null, this.cache[cacheId] = result);
|
37 | callback();
|
38 | });
|
39 | });
|
40 | }
|
41 | };
|