Skip to content

Instantly share code, notes, and snippets.

@basetdd2416
Last active December 17, 2018 13:26
Show Gist options
  • Save basetdd2416/4bcad67d468905d8cecf6dd4d409a708 to your computer and use it in GitHub Desktop.
Save basetdd2416/4bcad67d468905d8cecf6dd4d409a708 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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment