forked from spring-media/aws-lambda-router
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
60 lines (54 loc) · 2.47 KB
/
index.js
File metadata and controls
60 lines (54 loc) · 2.47 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
"use strict";
function handler(routeConfig) {
const eventProcessorMapping = extractEventProcessorMapping(routeConfig);
return (event, context, callback) => {
if (routeConfig.debug) {
console.log("Lambda invoked with request:", event);
console.log("Lambda invoked with context:", context);
}
for (const eventProcessorName of eventProcessorMapping.keys()) {
try {
// the contract of 'processors' is as follows:
// - their method 'process' is called with (config, event)
// - the method...
// - returns null: the processor does not feel responsible for the event
// - throws Error: the 'error.toString()' is taken as the error message of processing the event
// - returns object: this is taken as the result of processing the event
// - returns promise: when the promise is resolved, this is taken as the result of processing the event
const result = eventProcessorMapping.get(eventProcessorName)(routeConfig[eventProcessorName], event, context);
if (result) {
// be resilient against a processor returning a value instead of a promise:
return Promise.resolve(result)
.then(result => callback(null, result))
.catch(error => {
console.log(error.stack);
callback(error.toString());
});
} else {
if (routeConfig.debug) {
console.log("Event processor couldn't handle request.")
}
}
} catch (error) {
if (error.stack) {
console.log(error.stack);
}
callback(error.toString());
return;
}
}
callback('No event processor found to handle this kind of event!');
}
}
function extractEventProcessorMapping(routeConfig) {
const processorMap = new Map();
for (let key of Object.keys(routeConfig)) {
try {
processorMap.set(key, require(`./lib/${key}`));
} catch (error) {
throw new Error(`The event processor '${key}', that is mentioned in the routerConfig, cannot be instantiated (${error.toString()})`);
}
}
return processorMap;
}
module.exports = {handler: handler};