Created
July 2, 2019 18:40
-
-
Save maswadkar/678694bb46a259c5111ea6475e0f771a to your computer and use it in GitHub Desktop.
Reusing the Database Connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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