Skip to content

Commit

Permalink
Extract database connection to a function in the model/database module
Browse files Browse the repository at this point in the history
  • Loading branch information
iamleeg committed Apr 19, 2022
1 parent b1cc188 commit eba2789
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 20 deletions.
22 changes: 2 additions & 20 deletions verification/curator-service/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import validateEnv from './util/validate-env';
import { logger } from './util/logger';
import S3 from 'aws-sdk/clients/s3';
import cors from 'cors';
import { connectToDatabase } from './model/database';

const app = express();

Expand All @@ -57,26 +58,7 @@ app.set('port', env.PORT);
// MONGO_URL is provided by the in memory version of jest-mongodb.
// DB_CONNECTION_STRING is what we use in prod.
const mongoURL = process.env.MONGO_URL || env.DB_CONNECTION_STRING;
logger.info(
'Connecting to MongoDB instance',
// Print only after username and password to not log them.
mongoURL.substring(mongoURL.indexOf('@')),
);

mongoose
.connect(mongoURL, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => {
logger.info('Connected to the database');
})
.catch((e) => {
logger.error('Failed to connect to DB', e);
process.exit(1);
});
connectToDatabase(mongoURL);

// Store session info in MongoDB.
const MongoStore = mongo(session);
Expand Down
24 changes: 24 additions & 0 deletions verification/curator-service/api/src/model/database.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
import mongoose from 'mongoose';
import { logger } from '../util/logger';

export function connectToDatabase(mongoURL: string) {
logger.info(
'Connecting to MongoDB instance',
// Print only after username and password to not log them.
mongoURL.substring(mongoURL.indexOf('@'))
);

mongoose
.connect(mongoURL, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => {
logger.info('Connected to the database');
})
.catch((e) => {
logger.error('Failed to connect to DB', e);
process.exit(1);
});
}

export default () => mongoose.connection.getClient().db();

0 comments on commit eba2789

Please sign in to comment.