我正试图在我的类型记录项目中添加一个缓存层。当我搜索时,我发现了一篇关于媒体的文章
他通过向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;
};然后在mongoose.Query.prototype.exec中检查是否启用了查询缓存。
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;
};现在,通过调用mongoose查询中的cache()函数来启用缓存
books = await Book.find({ author: req.query.author }).cache();一切正常,然后我尝试将它转换成类型记录,但我不知道如何为它添加类型定义
打字本版本总是出现错误。
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>',有没有办法将这些类型添加到“查询”中?请帮助我
发布于 2022-08-03 18:42:22
我最终通过以下操作获得了这个效果。还请参见https://stackoverflow.com/a/70656849/1435970
创建文件/src/@types/mongoose.d.ts并向其添加以下内容:
type CacheOptions = {key?: string; time?: number}
declare module 'mongoose' {
interface DocumentQuery<T, DocType extends import('mongoose').Document, QueryHelpers = {}> {
mongooseCollection: {
name: any
}
cache(options?: CacheOptions): any
useCache: boolean
hashKey: string
}
interface Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> extends DocumentQuery<any, any> {}
}https://stackoverflow.com/questions/64980067
复制相似问题