I have been exploring ways to incorporate a cache layer into my TypeScript project. Recently, I came across an insightful article on Medium titled How to add a Redis cache layer to Mongoose in Node.js
The author demonstrates adding a caching function to mongoose.Query.prototype
:
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;
};
Subsequently, within mongoose.Query.prototype.exec
, the query checks if caching is enabled:
mongoose.Query.prototype.exec = async function() {
if (!this.useCache) {
return await exec.apply(this, arguments);
}
const key = JSON.stringify({
...this.getFilter(),
});
console.log(this.getFilter());
console.log(this.hashKey);
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);
return result;
};
To enable caching, simply call the cache()
function in the mongoose query:
books = await Book.find({ author: req.query.author }).cache();
While everything functions correctly, I encountered challenges while attempting to convert it to TypeScript. Specifically, I am uncertain about how to include type definitions for it.
The TypeScript version consistently presents errors such as:
Property 'cache' does not exist on type 'Query<any>',
Property 'useCache' does not exist on type 'Query<any>',
Property 'hashKey' does not exist on type 'Query<any>',
If anyone has suggestions on incorporating these types into 'Query', your assistance would be greatly appreciated.