Skip to content

Commit

Permalink
fix: Remove instanceof comparison for MongoDB DB instance check
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
stieg committed Feb 12, 2020
1 parent 07f7804 commit 171b358
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,33 +92,36 @@ export class Migration {
* @memberof Migration
*/
public async config(opts?: IMigrationOptions): Promise<void> {

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;
Expand Down

0 comments on commit 171b358

Please sign in to comment.