-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache-function.js
63 lines (58 loc) · 1.84 KB
/
cache-function.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 cacheManager = require('cache-manager');
const mongoStore = require('cache-manager-mongodb');
const objectHash = require('object-hash');
const request = require('request');
const fli = require('fli-webtask');
const _ = fli.npm.lodash;
const DEFAULT_TTL = 3600; // sec. => one hour
let _mongoCacheStore = {};
const createMongoCache = (context) => {
const store = _.get(context, 'query.store', 'db');
if(!_mongoCacheStore[store]) {
const uri = _.get(context.secrets, store, context.secrets.db);
_mongoCacheStore[store] = cacheManager.caching({
store: mongoStore,
uri: uri,
ignoreCacheErrors: true,
options: {
collection: 'cacheManager',
useUnifiedTopology: true
}
});
}
return _mongoCacheStore[store];
};
const fetchRequest = (options, next) => {
request(options, (err, res, body) => {
next(err, body);
});
};
const fetchFromCache = (context) => (mongoCache, next) => {
const options = _.get(context, 'body', {});
const key = objectHash(options);
const queryTtl = +_.get(context, 'query.ttl');
const ttl = _.isInteger(queryTtl) ? queryTtl : DEFAULT_TTL;
mongoCache.wrap(key, (cacheCallback) => {
fetchRequest(options, cacheCallback);
}, { ttl }, next);
};
/**
* @param context {WebtaskContext}
*/
module.exports = (context, cb) => {
const token = _.get(context, 'body.qs.token', _.get(context, 'query.token'));
if(context.secrets.token !== token) {
return cb('No token.');
}
if(!context.body) {
return cb('No body options for request.');
}
const mongoCache = createMongoCache(context);
// context.body -> https://www.npmjs.com/package/request#requestoptions-callback
return fetchFromCache(context)(mongoCache, (err, result) => {
if(!err && result) {
try { result = JSON.parse(result);} catch(e) { /**/ }
}
return cb(err, result);
});
};