Skip to content

Instantly share code, notes, and snippets.

@basetdd2416
Created December 17, 2018 13:29
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 basetdd2416/83cf6afd4d3d54b47dfb1414606d098b to your computer and use it in GitHub Desktop.
Save basetdd2416/83cf6afd4d3d54b47dfb1414606d098b to your computer and use it in GitHub Desktop.
// services/cache.js
const mongoose = require('mongoose');
const redis = require('redis');
const util = require('util');
const keys = require('../config/keys');
const client = redis.createClient(keys.redisUrl);
client.hget = util.promisify(client.hget);
const exec = mongoose.Query.prototype.exec;
mongoose.Query.prototype.cache = function(options = {}) {
this.useCache = true;
this.hashKey = JSON.stringify(options.key || '');
return this;
};
mongoose.Query.prototype.exec = async function() {
if (!this.useCache) {
return exec.apply(this, arguments);
}
const key = JSON.stringify(
Object.assign({}, this.getQuery(), {
collection: this.mongooseCollection.name
})
);
// See if we have a value for 'key' in redis
const cacheValue = await client.hget(this.hashKey, key);
// If we do, return that
if (cacheValue) {
const doc = JSON.parse(cacheValue);
return Array.isArray(doc)
? doc.map(d => new this.model(d))
: new this.model(doc);
}
// Otherwise, issue the query and store the result in redis
const result = await exec.apply(this, arguments);
client.hset(this.hashKey, key, JSON.stringify(result), 'EX', 10);
return result;
};
module.exports = {
clearHash(hashKey) {
client.del(JSON.stringify(hashKey));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment