Created
March 13, 2019 20:20
-
-
Save kobalski/70cc30280dccd7e3efd291089aa47a68 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
"use strict"; | |
const thundra = require("@thundra/core")(); | |
const MongoClient = require('mongodb').MongoClient; | |
const MONGODB_URI = process.env.MONGODB_URI; | |
let cachedDb = null; | |
function connectToDatabase (uri) { | |
console.log('=> connect to database'); | |
if (cachedDb) { | |
console.log('=> using cached database instance'); | |
return Promise.resolve(cachedDb); | |
} | |
return MongoClient.connect(uri) | |
.then(db => { | |
cachedDb = db; | |
return cachedDb; | |
}); | |
} | |
function queryDatabase (db) { | |
console.log('=> query database'); | |
return db.db("test").collection('items').find({}).toArray() | |
.then(() => { return { statusCode: 200, body: 'success' }; }) | |
.catch(err => { | |
console.log('=> an error occurred: ', err); | |
return { statusCode: 500, body: 'error' }; | |
}); | |
} | |
module.exports.handler = thundra((event, context, callback) => { | |
context.callbackWaitsForEmptyEventLoop = false; | |
console.log('event: ', event); | |
connectToDatabase(MONGODB_URI) | |
.then(db => queryDatabase(db)) | |
.then(result => { | |
console.log('=> returning result: ', result); | |
context.done(null, result); | |
}) | |
.catch(err => { | |
console.log('=> an error occurred: ', err); | |
context.fail(error); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment