forked from ned-kelly/serverless-offline-direct-lambda
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
106 lines (96 loc) · 2.9 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
98
99
100
101
102
103
104
105
106
"use strict";
const { lambda, buildLambdaName } = require("./helpers");
const packagePath = "node_modules/serverless-offline-lambda-invoke";
const handlerPath = `proxy.js`;
function AWS_SDK_METHOD(functionBeingProxied, location) {
var AWS_SDK_NODE_METHOD = {
http: {
method: "POST",
// This is the path to the Lambda API..
path: `2015-03-31/functions/${functionBeingProxied.name}/invocations`,
integration: "lambda",
request: {
template: {
// NB: AWS SDK for NodeJS specifies as 'binary/octet-stream' not 'application/json'
"binary/octet-stream": JSON.stringify({
location,
body: "$input.body",
targetHandler: functionBeingProxied.handler
})
}
},
response: {
headers: {
"Content-Type": "application/json"
}
}
}
};
return AWS_SDK_NODE_METHOD;
}
class ServerlessPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.hooks = {
"before:offline:start:init": this.startHandler.bind(this)
};
}
startHandler() {
let location = "";
try {
location = this.serverless.service.custom["serverless-offline"].location;
this.serverless.service.custom["serverless-offline"].location = "";
} catch (_) {}
this.serverless.cli.log(
"Running Serverless Offline with direct lambda support"
);
addProxies(this.serverless.service.functions, location);
}
}
const addProxies = (functionsObject, location) => {
Object.keys(functionsObject).forEach(fn => {
// filter out functions with event config,
// leaving just those intended for direct lambda-to-lambda invocation
const functionObject = functionsObject[fn];
if (!functionObject.events || functionObject.events.length === 0) {
const pf = functionProxy(functionObject, location);
functionsObject[pf.name] = pf;
}
});
};
const functionProxy = (functionBeingProxied, location) => ({
name: `${functionBeingProxied.name}_proxy`,
handler: `${packagePath}/proxy.handler`,
environment: functionBeingProxied.environment,
events: [
// This is the original `/post/FUNCTION-NAME` from the plugin...
{
http: {
method: "POST",
path: `proxy/${functionBeingProxied.name}`,
integration: "lambda",
request: {
template: {
"application/json": JSON.stringify({
location,
body: "$input.json('$')",
targetHandler: functionBeingProxied.handler
})
}
},
response: {
headers: {}
}
}
},
// See methods above for further details
AWS_SDK_METHOD(functionBeingProxied, location)
],
package: {
include: [handlerPath]
}
});
module.exports = ServerlessPlugin;
module.exports.lambda = lambda;
module.exports.buildLambdaName = buildLambdaName;