我正在尝试扩展mongoose查询函数,以便能够将缓存函数附加到mongoose查询。我已经完成了JavaScript的实现,但是当我尝试用typescript实现它时,会遇到不同的错误
JavaScript代码是:
const mongoose = require('mongoose');
const exec = mongoose.Query.prototype.exec;
const redisClient = require('./RedisClient');
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.getFilter(), {
collection: this.mongooseCollection.name
}));
const cachedValue = await redisClient.getHCache(this.hashKey, key);
if (cachedValue) {
const doc = JSON.parse(cachedValue);
return Array.isArray(doc)
? doc.map(d => new this.model(d))
: new this.model(doc);
}
const result = await exec.apply(this, arguments);
await redisClient.setHCache(this.hashKey, key, JSON.stringify(result));
return result;
}
字符串
我的typescript实现是
import mongoose, { Query } from 'mongoose';
import RedisClient from './redisClient';
declare module 'mongoose' {
interface Query<T> {
useCache?: boolean;
hashKey?: string;
cache(options?: { key?: unknown }): Query<T>;
}
}
const exec = Query.prototype.exec;
Query.prototype.cache = function (options = {}): Query<any> {
this.useCache = true;
this.hashKey = JSON.stringify(options.key || '');
return this;
};
Query.prototype.exec = async function (): Promise<any> {
if (!this.useCache) {
return exec.apply(this, arguments);
}
const key = JSON.stringify(Object.assign({}, this.getFilter(), {
collection: this.mongooseCollection.name,
}));
const cachedValue = await RedisClient.getHCache(this.hashKey, key);
if (cachedValue) {
const doc = JSON.parse(cachedValue);
return Array.isArray(doc)
? doc.map((d: any) => new this.model(d))
: new this.model(doc);
}
const result = await exec.apply(this, arguments);
await RedisClient.setHCache(this.hashKey, key, JSON.stringify(result));
return result;
};
型
我得到的错误是;
“Query”的所有声明必须具有相同的类型参数。
“IArguments”类型的参数不能分配给“[]”类型的参数
类型“Query<any,any,any,any,any,any>”上不存在属性“mongooseCollection”。你是说mongooseoptions吗?
请协助
1条答案
按热度按时间mklgxw1f1#
以下是正确的方法,同时也解释了更改的原因-
字符串
这里有一个链接到操场。