Created
March 13, 2019 19:58
-
-
Save kobalski/fc7c11abc5492c3d20be236fca7cee6b 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); | |
callback(null, result); | |
}) | |
.catch(err => { | |
console.log('=> an error occurred: ', err); | |
callback(err); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment