diff --git a/.changeset/shaggy-cycles-compare.md b/.changeset/shaggy-cycles-compare.md new file mode 100644 index 00000000..f4102cc5 --- /dev/null +++ b/.changeset/shaggy-cycles-compare.md @@ -0,0 +1,5 @@ +--- +'@tirke/node-cache-manager-mongodb': minor +--- + +Add possibility to pass a Mongo Client to the constructor diff --git a/.eslintrc.json b/.eslintrc.json index 41705cef..61e37e68 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -43,16 +43,14 @@ "newlines-between": "always" } ], - "@typescript-eslint/no-extra-semi": "error", - "no-extra-semi": "off" + "no-extra-semi": "error" } }, { "files": ["*.js", "*.jsx"], "extends": ["plugin:@nx/javascript"], "rules": { - "@typescript-eslint/no-extra-semi": "error", - "no-extra-semi": "off" + "no-extra-semi": "error" } } ] diff --git a/packages/node-cache-manager-mongodb/src/lib/node-cache-manager-mongodb.spec.ts b/packages/node-cache-manager-mongodb/src/lib/node-cache-manager-mongodb.spec.ts index 3522824d..38031e99 100644 --- a/packages/node-cache-manager-mongodb/src/lib/node-cache-manager-mongodb.spec.ts +++ b/packages/node-cache-manager-mongodb/src/lib/node-cache-manager-mongodb.spec.ts @@ -1,4 +1,5 @@ import { caching } from 'cache-manager' +import { MongoClient } from 'mongodb' import { mongoDbStore, MongoCache } from './node-cache-manager-mongodb' @@ -325,3 +326,15 @@ describe('databaseName', () => { await baseCache.reset() }) }) + +describe('reusing Mongo client', () => { + it('should reuse the client', async () => { + const mongoClient = new MongoClient('mongodb://localhost:27017') + const cache = await caching(mongoDbStore, { + client: mongoClient, + }) + + await cache.set('foo', 'bar') + expect(cache.store.client).toEqual(mongoClient) + }) +}) diff --git a/packages/node-cache-manager-mongodb/src/lib/node-cache-manager-mongodb.ts b/packages/node-cache-manager-mongodb/src/lib/node-cache-manager-mongodb.ts index 43cf6569..20d4d36e 100644 --- a/packages/node-cache-manager-mongodb/src/lib/node-cache-manager-mongodb.ts +++ b/packages/node-cache-manager-mongodb/src/lib/node-cache-manager-mongodb.ts @@ -19,6 +19,7 @@ type Args = { mongoConfig?: MongoClientOptions collectionName?: string databaseName?: string + client?: MongoClient } & Config @@ -36,7 +37,9 @@ class MongoDb implements MongoDbStore { this.isCacheable = args.isCacheable || ((value: unknown) => value !== undefined && value !== null) this.collectionName = args.collectionName || 'cache' this.databaseName = args.databaseName || 'cache' - if (args.url && args.mongoConfig) { + if (args.client) { + this.client = args.client + } else if (args.url && args.mongoConfig) { this.client = new MongoClient(args.url, args.mongoConfig) } else if (!args.url && args.mongoConfig) { this.client = new MongoClient('mongodb://localhost:27017', args.mongoConfig)