Last active
January 10, 2023 15:49
-
-
Save haimrait/7bc6b56ce3e16fce8e70d11665a98b17 to your computer and use it in GitHub Desktop.
node-redis-mongo - final cache
This file contains hidden or 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.hget = util.promisify(client.hget); | |
const exec = mongoose.Query.prototype.exec; | |
mongoose.Query.prototype.cache = function(options = { time: 60 }) { | |
this.useCache = true; | |
this.time = options.time; | |
this.hashKey = JSON.stringify(options.key || this.mongooseCollection.name); | |
return this; | |
}; | |
mongoose.Query.prototype.exec = async function() { | |
if (!this.useCache) { | |
return await exec.apply(this, arguments); | |
} | |
const key = JSON.stringify({ | |
...this.getQuery() | |
}); | |
const cacheValue = await client.hget(this.hashKey, 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); | |
console.log(this.time); | |
client.hset(this.hashKey, key, JSON.stringify(result)); | |
client.expire(this.hashKey, this.time); | |
console.log("Response from MongoDB"); | |
return result; | |
}; | |
module.exports = { | |
clearKey(hashKey) { | |
client.del(JSON.stringify(hashKey)); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment