Last active
February 14, 2019 15:53
-
-
Save simonaco/65da1d15decc376fe0ca35beee6cccaa to your computer and use it in GitHub Desktop.
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 MongoClient = require('mongodb').MongoClient; | |
// Initialize authentication details required for database connection | |
const auth = { | |
user: process.env.user, | |
password: process.env.password | |
}; | |
// Initialize global variable to store database connection for reuse in future calls | |
let db = null; | |
const loadDB = async () => { | |
// If database client exists, reuse it | |
if (db) { | |
return db; | |
} | |
// Otherwise create new connection | |
const client = await MongoClient.connect( | |
process.env.url, | |
{ | |
auth: auth | |
} | |
); | |
// Select tacos database | |
db = client.db('tacos'); | |
return db; | |
}; | |
module.exports = async function(context, req) { | |
try { | |
// Get database connection | |
const database = await loadDB(); | |
// Retrieve all items in the Recipes collection | |
let recipes = await database | |
.collection('Recipes') | |
.find() | |
.toArray(); | |
// Return a json object with the array of recipes | |
context.res = { | |
body: { items: recipes } | |
}; | |
} catch (error) { | |
context.log(`Error code: ${error.code} message: ${error.message}`); | |
// Return an error message and Internal Server Error status code | |
context.res = { | |
status: 500, | |
body: { message: 'An error has occured, please try again later' } | |
}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment