Last active
January 4, 2020 16:12
-
-
Save haimrait/9b1376dd77fffb26e2981d6d86938485 to your computer and use it in GitHub Desktop.
node-redis-mongo - A first cahce file implementation with hook for every query
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 mongoose = require("mongoose"); | |
const redis = require("redis"); | |
const util = require("util"); | |
const keys = require("../config/keys"); | |
const client = redis.createClient({ | |
host: keys.redisHost, | |
port: keys.redisPort, | |
retry_strategy: () => 1000 | |
}); | |
client.get = util.promisify(client.get); | |
const exec = mongoose.Query.prototype.exec; | |
mongoose.Query.prototype.exec = async function() { | |
const key = JSON.stringify({ | |
...this.getQuery() | |
}); | |
const cacheValue = await client.get(key); | |
if (cacheValue) { | |
const doc = JSON.parse(cacheValue); | |
console.log("Response from Redis"); | |
return Array.isArray(doc) | |
? doc.map(d => new this.model(d)) | |
: new this.model(doc); | |
} | |
const result = await exec.apply(this, arguments); | |
client.set(key, JSON.stringify(result)); | |
console.log("Response from MongoDB"); | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment