Last active
March 11, 2020 02:37
-
-
Save raphaellondner-mongodb/95a0e08b4a916fe8868928a1ba3134d5 to your computer and use it in GitHub Desktop.
MongoDB-Lambda-Example
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 AWS = require('aws-sdk'); | |
var MongoClient = require('mongodb').MongoClient; | |
let atlas_connection_uri; | |
exports.handler = (event, context, callback) => { | |
var uri = process.env['MONGODB_ATLAS_CLUSTER_URI']; | |
if (atlas_connection_uri != null) { | |
processEvent(event, context, callback); | |
} | |
else { | |
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'); | |
processEvent(event, context, callback); | |
}); | |
} | |
}; | |
function processEvent(event, context, callback) { | |
console.log('Calling MongoDB Atlas from AWS Lambda with event: ' + JSON.stringify(event)); | |
var jsonContents = JSON.parse(JSON.stringify(event)); | |
//date conversion for grades array | |
if(jsonContents.grades != null) { | |
for(var i = 0, len=jsonContents.grades.length; i < len; i++) { | |
//use the following line if you want to preserve the original dates | |
//jsonContents.grades[i].date = new Date(jsonContents.grades[i].date); | |
//the following line assigns the current date so we can more easily differentiate between similar records | |
jsonContents.grades[i].date = new Date(); | |
} | |
} | |
try | |
{ | |
MongoClient.connect(atlas_connection_uri, function(err, db) | |
{ | |
createDoc(db, jsonContents, callback); | |
}); | |
} | |
catch(err) | |
{ | |
console.error('an error occurred', err); | |
} | |
} | |
function createDoc (db, json, callback) { | |
db.collection('restaurants').insertOne( json, function(err, result) { | |
if(err!=null) { | |
console.error("an error occurred in createDoc", err); | |
callback(null, JSON.stringify(err)); | |
} | |
else { | |
console.log("Kudos! You just created an entry into the restaurants collection with id: " + result.insertedId); | |
callback(null, "SUCCESS"); | |
} | |
db.close(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment