Created
March 16, 2017 21:01
-
-
Save clifton/a087bd3b8ea7695dc96f559cb74780ad to your computer and use it in GitHub Desktop.
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 _ = require('lodash'); | |
export default class MemcachedStore { | |
constructor (memcached, { keyPrefix, ttl = 15 * 60 }) { | |
this.memcached = memcached; | |
this.keyPrefix = keyPrefix; | |
this.ttl = ttl; | |
this.queuedGets = {}; | |
} | |
toCacheKey(key) { | |
if (!this.keyPrefix) return key; | |
return `${this.keyPrefix}:${key}`; | |
} | |
get(key) { | |
const cacheKey = this.toCacheKey(key); | |
return new Promise((resolve, reject) => { | |
if (Object.keys(this.queuedGets).length === 0) { | |
process.nextTick(this.executeMulti.bind(this)); | |
} | |
if (!this.queuedGets[cacheKey]) { | |
this.queuedGets[cacheKey] = { resolves: [], rejects: [] }; | |
} | |
this.queuedGets[cacheKey].resolves.push(resolve); | |
this.queuedGets[cacheKey].rejects.push(reject); | |
}); | |
} | |
executeMulti() { | |
const gets = this.queuedGets; | |
this.queuedGets = {}; | |
console.log(_.mapValues(gets, ({ key }) => key)); | |
this.memcached.getMulti(Object.keys(gets), (err, data) => { | |
if (err) { | |
_.mapValues(gets, ({ rejects }) => rejects.forEach(r => r(err))); | |
return; | |
} | |
_.toPairs(gets).forEach( | |
([key, { resolves }]) => resolves.forEach(r => r(data[key])) | |
); | |
}); | |
} | |
set (key, value, ttl) { | |
ttl = ttl || this.ttl; | |
const cacheKey = this.toCacheKey(key); | |
return new Promise((resolve, reject) => { | |
this.memcached.set(cacheKey, value, ttl, (err) => { | |
if (err) { | |
reject(err); | |
return; | |
} | |
resolve(); | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment