From 171b358584b955426feb8bbadb97c6361975789b Mon Sep 17 00:00:00 2001 From: "Andrew Stiegmann (stieg)" Date: Wed, 12 Feb 2020 12:39:51 -1000 Subject: [PATCH] fix: Remove instanceof comparison for MongoDB DB instance check We can not reasonably use an `instanceof` comparison to confirm that a given object is of type MongoDB since we may be using a different version of MongoDB than what a caller might be using. In this scenario the check would fail. Thus this patch checks if a required field in the IDbProperties object is set. This required field is not a known field in MongoDB instance, thus it is arguably sane to check it in this manner. --- src/migration.ts | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/migration.ts b/src/migration.ts index 4b13607..d133f60 100644 --- a/src/migration.ts +++ b/src/migration.ts @@ -92,33 +92,36 @@ export class Migration { * @memberof Migration */ public async config(opts?: IMigrationOptions): Promise { - this.options = Object.assign({}, this.options, opts); if (!this.options.logger && this.options.log) { // tslint:disable-next-line: no-console this.options.logger = (level: string, ...args) => console.log(level, ...args); } + if (this.options.log === false) { // tslint:disable-next-line:no-empty this.options.logger = (level: string, ...args) => { }; } - if (!(this.db instanceof Db) && !this.options.db) { - throw new ReferenceError('Option.db canno\'t be null'); + + let db: IDbProperties | Db = this.options.db || this.db; + if (!db) { + throw new ReferenceError('db option must be defined'); } - let db: IDbProperties | Db; - if (this.options.db instanceof Db) { - db = this.options.db; - } else { - const options = { ...this.options.db.options }; + + // Check if connectionUrl exists. If it does, assume its IDbProperties object + if ((db as IDbProperties).connectionUrl) { + let dbProps = db as IDbProperties; + const options = { ...dbProps.options }; if (options.useNewUrlParser !== false) { options.useNewUrlParser = true; } const client = await MongoClient.connect( - this.options.db.connectionUrl, + dbProps.connectionUrl, options, ); - db = client.db(this.options.db.name || undefined); + // XXX: This never gets disconnected. + db = client.db(dbProps.name); } this.collection = (db as Db).collection(this.options.collectionName); this.db = db as Db;