1

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.

3 Answers 3

4

I was searching for the same thing and found this great post that explains how you can leverage events to ensure the DB is connected before starting app.listen().

app.on('ready', function() { 
    app.listen(3000, function(){ 
        console.log("app is ready"); 
    }); 
});

mongoose.connect( "mongodb://localhost/mydb" );
mongoose.connection.once('open', function() { 
    // All OK - fire (emit) a ready event. 
    app.emit('ready'); 
});

You could put all your routes in a seperate module and:

app.on('ready', function() { 
    app.use('/', require('./routes'));
    app.listen(3000, function(){ 
        console.log("app is ready"); 
    }); 
});
Sign up to request clarification or add additional context in comments.

Comments

1

Just await mongoose.connect(await getKmsKey('MONGOURL'));.

Comments

1

You can use promise also

mongoose.connect(uri, options).then(
  () => { 
    /** ready to use. The `mongoose.connect()` promise resolves to undefined. */
    },
  err => {
    /** handle initial connection error */
    }
);

See http://mongoosejs.com/docs/promises.html for reference

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.