Created
May 8, 2018 13:16
-
-
Save Akryum/843c7975af7c16de8caf20bf3a9db8b9 to your computer and use it in GitHub Desktop.
Micro cache
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
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