I have configured the express.js app to run on AWS lambda. The database URL is stored and encrypted in the Amazon KMS service so if I want to use the URL then I have to decrypt the key using AWS KMS service.
// imports
import mongoose from 'mongoose';
import serverless from 'serverless-http';
// KMS promise
const getKmsKey = (key) => {
// implementation
return new Promoise((resolve, reject) => { /* KMS logic */ });
};
// initiate database connection
(async function(){
mongoose.connect(await getKmsKey('MONGOURL'));
mongoose.Promise = global.Promise;
})();
const app = express();
// EDIT: added missing app.get example
app.get('/status', async (req, res, next) => {
// I would like to make sure that mongoose is always initiated here
res.sendStatus(200);
});
module.exports.handler = serverless(app.default);
Which is the best strategy to make sure that database connection is established before any express route? I see that there exists sync library (https://www.npmjs.com/package/sync) but I think that it's too much overhead just for setting up the database connection and I don't want to use it anywhere else.
Edit:
app.get('/status', async (req, res, next) => { was missing in the original post.