Skip to content

Instantly share code, notes, and snippets.

@Akryum
Created May 8, 2018 13:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akryum/843c7975af7c16de8caf20bf3a9db8b9 to your computer and use it in GitHub Desktop.
Save Akryum/843c7975af7c16de8caf20bf3a9db8b9 to your computer and use it in GitHub Desktop.
Micro cache
const LRU = require('lru-cache')
// Micro-caching
exports.cache = function (resolver, keyFactory, { max = 500, maxAge = 3000, perUser = true } = {}) {
const microCache = new LRU({
max,
maxAge,
})
return async (holder, args, context) => {
let key = typeof keyFactory === 'function' ? keyFactory(holder, args, context) : keyFactory
if (perUser) key = `${context.userId}:${key}`
let result = microCache.get(key)
if (!result) {
result = await resolver(holder, args, context)
microCache.set(key, result)
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment