Created
January 13, 2022 02:23
-
-
Save loucadufault/27a844073a6c91bf1e900fee127c0290 to your computer and use it in GitHub Desktop.
A simple pattern for opening a mongoose connection to a MongoDB database while registering listeners on the connection and handling the asynchronous result of opening the connection.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mongoose from "mongoose"; | |
function getConnection(databaseURL, connectionListeners) { | |
return mongoose.connection; | |
} | |
async function openConnection(databaseURL, options) { | |
await mongoose.connect(databaseURL, options); | |
} | |
export { getConnection, openConnection }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { getConnection, openConnection } from "./database"; | |
const databaseURL = process.env.DATABASE_URL; | |
const dbConnection = getConnection(); | |
dbConnection.on( | |
"error", | |
logger.error.bind(logger, "mongoDB connection error:") | |
); | |
dbConnection.once("open", () => { | |
logger.info("Connected to MongoDB"); | |
}); | |
// avoid top-level await | |
openConnection(databaseURL).then( | |
(mongooseInstance) => { | |
logger.info("Ready to use mongoose instance"); | |
}, | |
(e) => { | |
logger.error("Initial mongoose connection error"); | |
unexpectedErrorHandler(e); | |
} | |
); | |
function exitHandler() { | |
if (server) { | |
server.close(() => { | |
logger.info("Server closed"); | |
process.exit(1); | |
}); | |
} else { | |
process.exit(1); | |
} | |
} | |
function unexpectedErrorHandler(error) { | |
logger.error(error); | |
exitHandler(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment