Skip to content

Commit

Permalink
fix: Remove db connections on disconnect
Browse files Browse the repository at this point in the history
db connections stored in `dbs` were not being removed on disconnect.  This was causing issues in unit tests for downstream projects.
  • Loading branch information
jrassa committed Aug 24, 2023
1 parent 46abe73 commit 44b1641
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
18 changes: 10 additions & 8 deletions src/lib/mongoose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,17 +130,19 @@ export const connect = async () => {
};

//Disconnect from Mongoose
export const disconnect = () => {
export const disconnect = async () => {
// Create defers for mongoose connections
const promises = _.values(dbs).map((d) => {
if (isMongoose(d) && d.disconnect) {
return d.disconnect().catch(() => Promise.resolve());
}
return Promise.resolve();
});
const promises = Object.values(dbs)
.filter(isMongoose)
.map((d) => d.disconnect().catch(() => Promise.resolve()));

// Wait for all to finish, successful or not
return Promise.all(promises);
await Promise.all(promises);

// Remove connections
for (const key of Object.keys(dbs)) {
delete dbs[key];
}
};

async function initializeModel(name: string, model: Model<unknown>) {
Expand Down
3 changes: 2 additions & 1 deletion src/test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable no-console */
import Mocha, { MochaOptions } from 'mocha';
import 'should';
import { hideBin } from 'yargs/helpers';
import yargs from 'yargs/yargs';

Expand Down Expand Up @@ -29,7 +30,7 @@ mongoose
console.info('Mongoose connected, proceeding with tests');

process.on('exit', () => {
mongoose.disconnect();
mongoose.disconnect().then();
});

// Create the mocha instance
Expand Down

0 comments on commit 44b1641

Please sign in to comment.