我试图通过重写exec方法并向mongoose查询原型添加一个cache方法来缓存我的一些查询。正在保存查询,但正在删除哈希
这是我的密码:
在cache.js中
const mongoose = require("mongoose");
const redis = require("redis");
const client = redis.createClient({ url: process.env.REDIS_URL });
const exec = mongoose.Query.prototype.exec;
const hget = client.hget;
client.hget = function (key, field) {
return new Promise((resolve, reject) => {
hget.apply(client, [
key,
field,
(err, val) => {
if (err) {
return reject(err);
}
resolve(val);
}
]);
});
};
mongoose.Query.prototype.cache = function (key) {
this.shouldCache = true;
this.hashKey = key || "default";
return this;
};
mongoose.Query.prototype.exec = async function () {
if (!this.shouldCache) {
return exec.apply(this, arguments);
}
const cacheKey = JSON.stringify({
collection: this.mongooseCollection.name,
...this.getQuery()
});
const cachedVal = await client.hget(this.hashKey, cacheKey);
if (cachedVal) {
const queryRes = JSON.parse(cachedVal);
return Array.isArray(queryRes)
? queryRes.map((doc) => {
this.model(doc);
})
: this.model(queryRes);
}
const queryRes = await exec.apply(this, arguments);
client.hset(this.hashKey, cacheKey, JSON.stringify(queryRes));
return queryRes;
};
const clearHash = (hashKey) => {
client.del(hashKey || "default");
};
const flushCache = () => {
return new Promise((resolve) => {
client.flushdb(() => {
resolve();
});
});
};
const disconnectToRedis = () => {
return new Promise((resolve) => {
client.quit(() => {
resolve();
});
});
};
module.exports = { clearHash, flushCache, disconnectToRedis };
在我的中间件中,在请求完成后清除哈希键:
const { clearHash } = require("../services/cache");
const clearCache = async (req, res, next) => {
await next();
console.log("clearing cache");
clearHash();
console.log("cleared cache");
};
module.exports = clearCache;
在我的路由文件中
const express = require("express");
const router = express.Router();
const clearCache = require("../middlewares/clearCache");
const AuthController = require("../controllers/Auth");
router.post("/register", clearCache, AuthController.register);
router.post("/login", AuthController.login);
router.get("/user", AuthController.getUser);
module.exports = router;
我使用了一个debugged来查看clearhash函数是否在处理请求之后被调用,它是,但它没有清除散列键。但是,如果我尝试从另一个文件调用该函数并尝试只运行该文件,则会清除哈希键。
我不知道怎么了。可能是某种导入错误。谢谢你的帮助。
暂无答案!
目前还没有任何答案,快来回答吧!