feat(database): add cache to mongoose adapter

This commit is contained in:
Slincnik 2024-12-16 17:41:39 +03:00
parent ac461a104d
commit c7ebdb78d4
No known key found for this signature in database

View file

@ -1,6 +1,7 @@
import mongoose from "mongoose";
import IDatabaseAdapter from "./IDatabaseAdapter.js";
import logger from "../../helpers/logger.js";
import Cache from "../cache/MapCache.js";
export default class MongooseAdapter extends IDatabaseAdapter {
/**
@ -16,8 +17,8 @@ export default class MongooseAdapter extends IDatabaseAdapter {
}
this.uri = uri;
this.options = options;
this.cache = new Cache();
}
async connect() {
@ -28,21 +29,44 @@ export default class MongooseAdapter extends IDatabaseAdapter {
async disconnect() {
await mongoose.disconnect();
logger.warn("Database disconnected.");
this.cache.clear();
}
#generateCacheKey(modelName, query, options) {
return `${modelName}:${JSON.stringify(query)}:${JSON.stringify(options)}`;
}
async find(model, query = {}, options = {}) {
return model.find(query, null, options).exec();
const cacheKey = this.#generateCacheKey(model.modelName, query, options);
if (this.cache.get(cacheKey)) {
return this.cache.get(cacheKey);
}
const result = await model.find(query, null, options).exec();
this.cache.set(cacheKey, result);
return result;
}
async findOne(model, query = {}, options = {}) {
return model.findOne(query, null, options).exec();
const cacheKey = this.#generateCacheKey(model.modelName, query, options);
if (this.cache.get(cacheKey)) {
return this.cache.get(cacheKey);
}
const result = await model.findOne(query, null, options).exec();
this.cache.set(cacheKey, result);
return result;
}
async updateOne(model, filter, update, options = {}) {
return model.updateOne(filter, update, options).exec();
const result = await model.updateOne(filter, update, options).exec();
this.cache.clear();
return result;
}
async deleteOne(model, filter) {
return model.deleteOne(filter).exec();
const result = await model.deleteOne(filter).exec();
this.cache.clear();
return result;
}
}