Skip to content

Instantly share code, notes, and snippets.

@maswadkar
Created July 2, 2019 18:40
Show Gist options
  • Save maswadkar/678694bb46a259c5111ea6475e0f771a to your computer and use it in GitHub Desktop.
Save maswadkar/678694bb46a259c5111ea6475e0f771a to your computer and use it in GitHub Desktop.
Reusing the Database Connection
const mongodb = require('mongodb');
const uri = 'mongodb+srv://OMITTED/test';
// May be retained between function executions depending on whether Azure
// cleans up memory
let client = null;
module.exports = function (context, req) {
context.log('Running');
let hasClient = client != null;
if (client == null) {
mongodb.MongoClient.connect(uri, function(error, _client) {
if (error) {
context.log('Failed to connect');
context.res = { status: 500, body: res.stack }
return context.done();
}
client = _client;
context.log('Connected');
query();
});
} else {
query();
}
function query() {
client.db('test').collection('tests').find().toArray(function(error, docs) {
if (error) {
context.log('Error running query');
context.res = { status: 500, body: res.stack }
return context.done();
}
context.log('Success!');
context.res = {
headers: { 'Content-Type': 'application/json' },
body: 'Num docs ' + docs.length + ', reused connection ' + hasClient
};
context.done();
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment