Reusing Database Connections With Azure Functions Using Javascript
I cannot find clear information on how to manage database connections (MongoDB in my case) from an Azure function written in Javascript. The Microsoft document below says to not
Solution 1:
Yes, there's a very close equivalence between C#/SQL storing a single SqlConnection instance in a static variable and JS/MongoDB storing a single Db instance in a global variable. The basic pattern for JS/MongoDB in Azure Functions is (assuming you're up to date for async/await - alternatively you can use callbacks as per your linked article):
// getDb.jslet dbInstance;
module.exports = asyncfunction() {
if (!dbInstance) {
dbInstance = awaitMongoClient.connect(uri);
}
return dbInstance;
};
// function.jsconst getDb = require('./getDb.js');
module.exports = asyncfunction(context, trigger) {
let db = awaitgetDb();
// ... do stuff with db ..
};
This will mean you only instantiate one Db object per host instance. Note this isn't one per Function App - if you're using a dedicated App Service Plan then there will be the number of instances you've specified in the plan, and if you're using a Consumption Plan then it'll vary depending on how busy your app is.
Post a Comment for "Reusing Database Connections With Azure Functions Using Javascript"