Skip to content

Instantly share code, notes, and snippets.

@clifton
Created March 16, 2017 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clifton/a087bd3b8ea7695dc96f559cb74780ad to your computer and use it in GitHub Desktop.
Save clifton/a087bd3b8ea7695dc96f559cb74780ad to your computer and use it in GitHub Desktop.
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