/
integration.js
267 lines (227 loc) · 7.78 KB
/
integration.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
'use strict';
const _ = require('lodash');
const DEFAULT_COMMON_TEMPLATE = `
#define( $loop )
{
#foreach($key in $map.keySet())
#set( $k = $util.escapeJavaScript($key) )
#set( $v = $util.escapeJavaScript($map.get($key)).replaceAll("\\\\'", "'") )
"$k":
"$v"
#if( $foreach.hasNext ) , #end
#end
}
#end
{
"body": $body,
"method": "$context.httpMethod",
"principalId": "$context.authorizer.principalId",
"stage": "$context.stage",
"cognitoPoolClaims" : {
extraCognitoPoolClaims
"sub": "$context.authorizer.claims.sub"
},
#set( $map = $context.authorizer )
"enhancedAuthContext": $loop,
#set( $map = $input.params().header )
"headers": $loop,
#set( $map = $input.params().querystring )
"query": $loop,
#set( $map = $input.params().path )
"path": $loop,
#set( $map = $context.identity )
"identity": $loop,
#set( $map = $stageVariables )
"stageVariables": $loop,
"requestPath": "$context.resourcePath"
}
`;
module.exports = {
getMethodIntegration(http, { lambdaLogicalId, lambdaAliasName }) {
const type = http.integration || 'AWS_PROXY';
const integration = {
IntegrationHttpMethod: 'POST',
Type: type,
};
// Valid integrations are:
// * `HTTP` for integrating with an HTTP back end,
// * `AWS` for any AWS service endpoints,
// * `MOCK` for testing without actually invoking the back end,
// * `HTTP_PROXY` for integrating with the HTTP proxy integration, or
// * `AWS_PROXY` for integrating with the Lambda proxy integration type (the default)
if (type === 'AWS' || type === 'AWS_PROXY') {
Object.assign(integration, {
Uri: {
'Fn::Join': [
'',
[
'arn:',
{ Ref: 'AWS::Partition' },
':apigateway:',
{ Ref: 'AWS::Region' },
':lambda:path/2015-03-31/functions/',
...[],
{ 'Fn::GetAtt': [lambdaLogicalId, 'Arn'] },
...(lambdaAliasName ? [':', lambdaAliasName] : []),
'/invocations',
],
],
},
});
} else if (type === 'HTTP' || type === 'HTTP_PROXY') {
const integrationHttpMethod = (http.request && http.request.method) || http.method;
Object.assign(integration, {
Uri: http.request && http.request.uri,
IntegrationHttpMethod: integrationHttpMethod.toUpperCase(),
});
if (http.connectionType) {
Object.assign(integration, {
ConnectionType: http.connectionType,
ConnectionId: http.connectionId,
});
}
} else if (type === 'MOCK') {
// nothing to do but kept here for reference
}
if (type === 'AWS' || type === 'HTTP' || type === 'MOCK') {
Object.assign(integration, {
PassthroughBehavior: http.request && http.request.passThrough,
ContentHandling: http.request && http.request.contentHandling,
RequestTemplates: this.getIntegrationRequestTemplates(http, type === 'AWS'),
IntegrationResponses: this.getIntegrationResponses(http),
});
}
if (
((type === 'AWS' || type === 'HTTP' || type === 'HTTP_PROXY') &&
http.request &&
http.request.parameters &&
Object.keys(http.request.parameters).length) ||
http.async
) {
Object.assign(integration, {
RequestParameters: this.getIntegrationRequestParameters(http),
});
}
return {
Properties: {
Integration: integration,
},
};
},
getIntegrationResponses(http) {
const integrationResponses = [];
if (http.response) {
const integrationResponseHeaders = [];
if (http.cors) {
let origin = http.cors.origin;
// TODO remove once "origins" config is deprecated
if (http.cors.origins && http.cors.origins.length) {
origin = http.cors.origins.join(',');
}
_.merge(integrationResponseHeaders, {
'Access-Control-Allow-Origin': `'${origin}'`,
});
// Only set Access-Control-Allow-Credentials when explicitly allowed (omit if false)
if (http.cors.allowCredentials) {
integrationResponseHeaders['Access-Control-Allow-Credentials'] = 'true';
}
}
if (http.response.headers) {
_.merge(integrationResponseHeaders, http.response.headers);
}
_.forEach(http.response.statusCodes, (config, statusCode) => {
const responseParameters = _.mapKeys(
integrationResponseHeaders,
(value, header) => `method.response.header.${header}`
);
const integrationResponse = {
StatusCode: statusCode,
SelectionPattern: config.pattern || '',
ResponseParameters: responseParameters,
ResponseTemplates: {},
ContentHandling: statusCode.startsWith('2') ? http.response.contentHandling : undefined,
};
if (config.headers) {
_.merge(
integrationResponse.ResponseParameters,
_.mapKeys(config.headers, (value, header) => `method.response.header.${header}`)
);
}
if (http.response.template) {
_.merge(integrationResponse.ResponseTemplates, {
'application/json': http.response.template,
});
}
if (config.template) {
const template =
typeof config.template === 'string'
? { 'application/json': config.template }
: config.template;
_.merge(integrationResponse.ResponseTemplates, template);
}
integrationResponses.push(integrationResponse);
});
}
return integrationResponses;
},
getIntegrationRequestTemplates(http, useDefaults) {
// default request templates
const integrationRequestTemplates = {};
// Only set defaults for AWS (lambda) integration
if (useDefaults) {
Object.assign(integrationRequestTemplates, {
'application/json': this.DEFAULT_JSON_REQUEST_TEMPLATE,
'application/x-www-form-urlencoded': this.DEFAULT_FORM_URL_ENCODED_REQUEST_TEMPLATE,
});
}
// set custom request templates if provided
if (http.request && typeof http.request.template === 'object') {
_.entries(http.request.template).forEach(([contentType, template]) => {
if (template === null) {
delete integrationRequestTemplates[contentType];
} else {
integrationRequestTemplates[contentType] = template;
}
});
}
return Object.keys(integrationRequestTemplates).length
? integrationRequestTemplates
: undefined;
},
getIntegrationRequestParameters(http) {
const parameters = {};
if (http.request && http.request.parameters) {
_.forEach(http.request.parameters, (value, key) => {
parameters[`integration.${key.substring('method.'.length)}`] = value.mappedValue || key;
});
}
if (http.async) {
parameters['integration.request.header.X-Amz-Invocation-Type'] = "'Event'";
}
return parameters;
},
DEFAULT_JSON_REQUEST_TEMPLATE: `
#set( $body = $input.json("$") )
${DEFAULT_COMMON_TEMPLATE}
`,
DEFAULT_FORM_URL_ENCODED_REQUEST_TEMPLATE: `
#define( $body )
{
#foreach( $token in $input.path('$').split('&') )
#set( $keyVal = $token.split('=') )
#set( $keyValSize = $keyVal.size() )
#if( $keyValSize >= 1 )
#set( $key = $util.escapeJavaScript($util.urlDecode($keyVal[0])) )
#if( $keyValSize >= 2 )
#set($val = $util.escapeJavaScript($util.urlDecode($keyVal[1])).replaceAll("\\\\'","'"))
#else
#set( $val = '' )
#end
"$key": "$val"#if($foreach.hasNext),#end
#end
#end
}
#end
${DEFAULT_COMMON_TEMPLATE}
`,
};