forked from middyjs/middy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.js
38 lines (34 loc) · 1.04 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
const { createHash } = require('crypto')
module.exports = (opts) => {
const defaultStorage = {}
const defaults = {
calculateCacheId: (event) => Promise.resolve(createHash('md5').update(JSON.stringify(event)).digest('hex')),
getValue: (key) => Promise.resolve(defaultStorage[key]),
setValue: (key, value) => {
defaultStorage[key] = value
return Promise.resolve()
}
}
const options = Object.assign({}, defaults, opts)
let currentCacheKey
return ({
before: (handler, next) => {
options.calculateCacheId(handler.event)
.then((cacheKey) => {
currentCacheKey = cacheKey
return options.getValue(cacheKey)
})
.then((cachedResponse) => {
if (typeof cachedResponse !== 'undefined') {
return handler.callback(null, cachedResponse)
}
return next()
})
},
after: (handler, next) => {
// stores the calculated response in the cache
options.setValue(currentCacheKey, handler.response)
.then(next)
}
})
}