-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp_final.js
More file actions
76 lines (67 loc) · 2.94 KB
/
app_final.js
File metadata and controls
76 lines (67 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict'
const AWS = require('aws-sdk');
var MongoClient = require('mongodb').MongoClient;
let atlas_connection_uri;
let cachedDb = null;
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));
//the following line is critical for performance reasons to allow re-use of database connections across calls to this Lambda function and avoid closing the database connection. The first call to this lambda function takes about 5 seconds to complete, while subsequent, close calls will only take a few hundred milliseconds.
context.callbackWaitsForEmptyEventLoop = false;
//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 {
if (cachedDb == null) {
console.log('=> connecting to database');
MongoClient.connect(atlas_connection_uri, function (err, db) {
cachedDb = db;
return createDoc(db, jsonContents, callback);
});
}
else {
createDoc(cachedDb, 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");
}
//we don't need to close the connection thanks to context.callbackWaitsForEmptyEventLoop = false (above)
//this will let our function re-use the connection on the next called (if it can re-use the same Lambda container)
//db.close();
});
};