diff --git a/src/adapters/database/MongooseAdapter.js b/src/adapters/database/MongooseAdapter.js index 56215eba..aa71f59c 100644 --- a/src/adapters/database/MongooseAdapter.js +++ b/src/adapters/database/MongooseAdapter.js @@ -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; } }