如何在express.js应用程序启动之前加载异步数据库URL并启动数据库连接?

时间:2018-01-23 08:31:58

标签: javascript node.js mongodb express mongoose

我已将express.js应用配置为在AWS lambda上运行。数据库URL在Amazon KMS服务中存储和加密,因此如果我想使用URL,则必须使用AWS KMS服务解密密钥。

// 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);

确保在任何快速路线之前建立数据库连接的最佳策略是什么?我看到存在同步库(https://www.npmjs.com/package/sync),但我认为仅仅为了设置数据库连接而且我不想在其他任何地方使用它。“/ p>

修改 原帖中遗失了app.get('/status', async (req, res, next) => {

3 个答案:

答案 0 :(得分:1)

只需await mongoose.connect(await getKmsKey('MONGOURL'));

答案 1 :(得分:1)

你也可以使用诺言

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

请参阅http://mongoosejs.com/docs/promises.html以获取参考资料

答案 2 :(得分:1)

我正在寻找同样的事情并发现这篇很棒的文章解释了你如何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'); 
});

您可以将所有路线放在一个单独的模块中:

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