forked from serverless/serverless
-
Notifications
You must be signed in to change notification settings - Fork 2
/
cors.js
78 lines (66 loc) · 2.26 KB
/
cors.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
'use strict';
const _ = require('lodash');
const BbPromise = require('bluebird');
module.exports = {
compileCors() {
_.forEach(this.validated.corsPreflight, (config, path) => {
const resourceName = this.getResourceName(path);
const resourceRef = this.getResourceId(path);
const corsMethodLogicalId = this.provider.naming
.getMethodLogicalId(resourceName, 'options');
const preflightHeaders = {
'Access-Control-Allow-Origin': `'${config.origins.join(',')}'`,
'Access-Control-Allow-Headers': `'${config.headers.join(',')}'`,
'Access-Control-Allow-Methods': `'${config.methods.join(',')}'`,
'Access-Control-Allow-Credentials': `'${config.allowCredentials}'`,
};
_.merge(this.serverless.service.provider.compiledCloudFormationTemplate.Resources, {
[corsMethodLogicalId]: {
Type: 'AWS::ApiGateway::Method',
Properties: {
AuthorizationType: 'NONE',
HttpMethod: 'OPTIONS',
MethodResponses: this.generateCorsMethodResponses(preflightHeaders),
RequestParameters: {},
Integration: {
Type: 'MOCK',
RequestTemplates: {
'application/json': '{statusCode:200}',
},
IntegrationResponses: this.generateCorsIntegrationResponses(preflightHeaders),
},
ResourceId: resourceRef,
RestApiId: { Ref: this.apiGatewayRestApiLogicalId },
},
},
});
});
return BbPromise.resolve();
},
generateCorsMethodResponses(preflightHeaders) {
const methodResponseHeaders = {};
_.forEach(preflightHeaders, (value, header) => {
methodResponseHeaders[`method.response.header.${header}`] = true;
});
return [
{
StatusCode: '200',
ResponseParameters: methodResponseHeaders,
ResponseModels: {},
},
];
},
generateCorsIntegrationResponses(preflightHeaders) {
const responseParameters = _.mapKeys(preflightHeaders,
(value, header) => `method.response.header.${header}`);
return [
{
StatusCode: '200',
ResponseParameters: responseParameters,
ResponseTemplates: {
'application/json': '',
},
},
];
},
};