I used a singleton in my code.
Exporting a promise
In one file I export a promise...
connection.js
const { createConnection } = require('mongoose');
function getConnection() {
return mongoose.createConnection(...).asPromise();
}
const connPromise = getConnection();
module.exports = connPromise;
other files...
const connPromise = require('./connection.js');
async function handler() {
// Connection starts on first module import
// This gets faster when the connection is done being created
const connection = await connPromise;
// Do stuff with the connection
return {
data: '',
and: '',
stuff: '',
};
}
When everything is shutting down, like in a lambda, also in connection.js:
process.on('SIGTERM', async () => {
console.info('[runtime] SIGTERM received');
const conn = await connPromise;
await conn.close();
console.info('[runtime] closed connection');
process.exit(0);
});
So by storing the connection in a promise, I can get it everywhere. I don't export the connection itself because getting it is async.
Exporting a getter function
I could have a function like
let connection = null;
function getConnection() {
if (!connection) {
connection = await createConnection(...).asPromise();
}
return connection;
}
module.exports = getConnection;
other files...
const getConnection = require('./connection.js');
async function handler() {
// Gets faster after the first call.
// connection created on first call.
const connection = await getConnection();
// Do stuff with the connection
return {
data: '',
and: '',
stuff: '',
};
}
Then your shutdown would become
process.on('SIGTERM', async () => {
console.info('[runtime] SIGTERM received');
if (connection) {
await connection.close();
console.info('[runtime] closed connection');
}
process.exit(0);
});
Summary
Overall, I like exporting the promise, since in every lambda function, I'm always using the database.
Since the exported promise means that the connection starts as soon as the module is imported, it's ready to go sooner than if I waited till the invocation of the getConnection()
in an event handler.
For having only one connection, this is a good way to get ahold of it.