Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function processEvent(event, context, callback) {
const storableEvent = makeEventStorable(event);
storableEvent.created_at = new Date();
console.log('Calling MongoDB Atlas from AWS Lambda: ', JSON.stringify(storableEvent));
if (cachedDb) {
console.log('- Reusing cached connection');
createDoc(cachedDb, storableEvent, callback);
return;
}
console.log('- Connecting to database');
MongoClient.connect(atlasConnectionUri, (err, db) => {
if (err) {
console.error('... Error: ', err);
callback(err);
return;
}
console.log('... Done');
cachedDb = db;
createDoc(cachedDb, storableEvent, callback);
});
}
function makeEventStorable(event) {
const data = {};
Object.keys(event).forEach((key) => {
if (key !== 'grades') {
data[key] = event[key];
return;
}
data[key] = event[key].map((grade) => {
grade.date = new Date(grade.date); // use real JS dates
return grade;
});
});
return data;
}
function createDoc(db, data, done) {
console.log('- Creating document');
db.collection('restaurants')
.insertOne(data, (err, result) => {
if (err) {
console.error('... Error: ', err);
return done(err);
}
console.log("... Done", result.insertedId);
done(null); // done() should work, but it doesn't in lambda-local (not in master)
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment