Skip to content

Instantly share code, notes, and snippets.

@uF4No uF4No/lambdaMongo.js
Created Dec 19, 2019

Embed
What would you like to do?
'use strict'
// To use AWS secrets
//const AWS = require('aws-sdk');
const MongoClient = require('mongodb').MongoClient
//Performance optimization Step 1: declare the database connection object outside
//the handler method so it's cached
let cachedDb = null
let atlas_connection_uri = null
exports.handler = async (event, context) => {
try {
var uri = process.env['MONGODB_ATLAS_CLUSTER_URI']
console.log('remaining time =', context.getRemainingTimeInMillis())
console.log('functionName =', context.functionName)
console.log('AWSrequestID =', context.awsRequestId)
console.log('logGroupName =', context.logGroupName)
console.log('logStreamName =', context.logStreamName)
console.log('clientContext =', context.clientContext)
//Performance optimization Step 2: set context.callbackWaitsForEmptyEventLoop to false
//to prevent the Lambda function from waiting for all resources (such as the database connection) to be released before returning it
context.callbackWaitsForEmptyEventLoop = false
if (atlas_connection_uri == null) {
atlas_connection_uri = uri
/* Use KMS to access AWS secrets
const kms = new AWS.KMS();
kms.decrypt({ CiphertextBlob: new Buffer(uri, 'base64') }, (err, data) => {
if (err) {
console.log('Decrypt error:', err);
return callback(err);
}
atlas_connection_uri = data.Plaintext.toString('ascii');
});
*/
}
const res = await processEvent(event)
console.log('Handler response is: ', res)
return res
} catch (error) {
console.log(error)
return error
}
}
async function processEvent(event) {
try {
const db = await connectToDatabase(atlas_connection_uri)
const result = await queryDatabase(db, event)
console.log('query results: ', result)
return result
} catch (err) {
console.log('Error processing event: ', err)
return err
}
}
async function connectToDatabase(uri) {
try {
//Performance optimization Step 3: test that database connection exists
// and is valid before re-using it
if (cachedDb && cachedDb.serverConfig.isConnected()) {
console.log('=> using cached database instance')
return cachedDb
}
const dbName = 'MY_DATABASE_NAME'
const client = await MongoClient.connect(uri)
cachedDb = client.db(dbName)
return cachedDb
} catch (error) {
console.log(error)
return error
}
}
async function queryDatabase(db, event) {
let response = {
isBase64Encoded: false,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' // IMPORTANT! setup this according to your domain
}
}
try {
var jsonContents = JSON.parse(JSON.stringify(event))
//handling API Gateway input where the event is embedded into the 'body' element
if (!event.body !== null && !event.body !== undefined) {
response.statusCode = 420
response.body = JSON.stringify({
message: 'Invalid input'
})
return response
}
console.log('retrieving payload from event.body')
jsonContents = JSON.parse(event.body)
if (!jsonContents.name && !jsonContents.email) {
response.statusCode = 420
response.body = JSON.stringify({
message: 'Missing params in request body'
})
return response
}
const now = new Date()
const dbResponse = await db.collection('Subscribers').insertOne({
name: jsonContents.name,
email: jsonContents.email,
createdAt: now,
updatedAt: now,
__v: 0
})
console.log('New Sub inserted: ', dbResponse)
response = {
statusCode: 201,
body: JSON.stringify({
message: 'Subscribed ok'
})
}
return response
} catch (error) {
console.log(error)
return error
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.