Created
January 6, 2024 10:53
-
-
Save Deepak13245/f69899361f81963e5c5883b2d8296031 to your computer and use it in GitHub Desktop.
cacheable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {HttpResponse} from "../utils"; | |
import {get} from "lodash"; | |
// compute cache key | |
function getCacheKey(req, options) { | |
if (typeof options.hashFn === 'function') { | |
return options.hashFn(req); | |
} | |
const {body, query} = req; | |
const keys = []; | |
options.body.forEach(key => { | |
keys.push(get(body, key)); | |
}); | |
options.query.forEach(key => { | |
keys.push(get(query, key)); | |
}); | |
options.headers.forEach(key => { | |
keys.push(req.get(key)); | |
}); | |
options.params.forEach(key => { | |
keys.push(req.params[key]); | |
}); | |
return keys.join(':'); | |
} | |
/** | |
* @param {function} hashFn | |
* @param {[string]} body | |
* @param {[string]} query | |
* @param {[string]} headers | |
* @param {[string]} params | |
*/ | |
export function Cacheable({ | |
hashFn, | |
body = [], | |
query = [], | |
headers = [], | |
params = [], | |
} = {}) { | |
return target => { | |
const original = target.descriptor.value; | |
target.descriptor.value = async function (req, res) { | |
const key = await getCacheKey(req, {body, query, headers, hashFn, params}); | |
const cached = await cache.get(key); | |
if (cached) { | |
return new HttpResponse(cached, 200, { | |
'x-cache': 'hit', | |
}); | |
} | |
const result = await original.apply(this, [req, res]); | |
await cache.set(key, result); | |
return new HttpResponse(result, 200, { | |
'x-cache': 'miss', | |
}); | |
}; | |
return target; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment