Skip to content

Instantly share code, notes, and snippets.

@Akryum

Akryum/cache.js

Created May 8, 2018
Embed
What would you like to do?
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