-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
97 lines (77 loc) · 2.94 KB
/
index.js
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"use strict";
const mongoose = require("mongoose");
const request = require('request-promise');
// DATABASE mongo URI should be set via Lambda env
const uri = process.env.DATABASE;
// scope dbconnection globally
let dbConnection = null;
// lambda entry handler
exports.handler = async function(event, context) {
context.callbackWaitsForEmptyEventLoop = false;
// if database connection not active, create it in global scope
if (dbConnection == null) {
dbConnection = await mongoose.createConnection(uri, {
bufferCommands: false,
bufferMaxEntries: 0,
useNewUrlParser: true,
useCreateIndex: true
});
// create model and attach to global database connection
const eventSchema = require('./models/event');
dbConnection.model('Event', eventSchema);
}
//swap out event for test file when in dev
if(process.env.TESTFILE) {
event = require(process.env.TESTFILE);
}
const webhookUri = process.env.LEGACY_WEBHOOK_URI;
// pull webhook uri from environment
const options = {
method: 'POST',
uri: webhookUri,
body: event,
json: true
};
await request(options);
const eventModel = dbConnection.model('Event');
// get event data from gateway passthrough
let eventData = event.body;
// if event data is a string, parse it
if(typeof eventData == "string") {
eventData = JSON.parse(eventData);
}
// separate unpacked fields and put everything else in eventData embedded data
const handledFields = Object.keys(eventModel.schema.obj);
eventData = eventData.map(event => {
let mappedEvent = { 'info': {} };
Object.keys(event).forEach(key => {
if (handledFields.indexOf(key) > -1) {
mappedEvent[key] = event[key];
} else {
mappedEvent.info[key] = event[key];
}
});
//mappedEvent.eventData = JSON.stringify(mappedEvent.eventData);
return mappedEvent;
});
// initialise return result
const result = { received: eventData.length, dupes: 0, errors: 0 };
await new Promise((resolve, reject) => {
// insert records
eventModel.insertMany(eventData, { ordered: false }, (error) => {
// count dupes and non-dupe errors
if(error && error.writeErrors) {
result.dupes = error.writeErrors.filter( error => error.err.code == 11000 ).length;
result.errors = error.writeErrors.length - result.dupes;
}
resolve(true);
});
});
if(result.errors > 0) {
console.error({ eventData: eventData, insertResult: result });
}
if(result.dupes > 0) {
console.warn({ eventData: eventData, insertResult: result });
}
return { "statusCode": result.errors ? 500 : 200, "body": result };
};