This repository has been archived by the owner on Mar 20, 2023. It is now read-only.
forked from Nedvedyy/serverless-apigateway-plugin
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
204 lines (194 loc) · 6 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
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
'use strict';
const Promise = require('bluebird');
const AWS = require('aws-sdk');
class APIGatewayCustomiser {
constructor(serverless, options) {
this.createDeploymentRetryDelay = options.createDeploymentRetryDelay || 5 * 1000;
this.serverless = serverless;
// this.options = options;
this.custom = this.serverless.service.custom;
this.hooks = {
'after:deploy:deploy': this.afterDeployFunctions.bind(this)
};
}
/**
* @description hook to after deployment
*
* @return {Promise}
*/
afterDeployFunctions() {
this.stage = this.serverless.service.provider.stage || 'dev';
this.region = this.serverless.service.provider.region || 'ap-southeast-1';
this.providerName = this.serverless.service.provider.name;
this.apiName = this.serverless.getProvider(this.providerName).naming.getApiGatewayName();
this.apiGatewaySDK = new AWS.APIGateway({ region: this.region });
return this.modifyAPIGateway();
}
/**
* @description modify the gateway
*/
modifyAPIGateway() {
this.serverless.cli.log('API Gateway Configuring: Start');
/** Filter functions for those need API Gateway Config */
if (this.custom.apigateway) {
return new Promise((resolve, reject) => {
this.apiGatewaySDK.getRestApis({ limit: 500 }, (err, data) => {
if (err) {
reject(err);
}
const api = data.items.find(entry => entry.name === this.apiName);
if (api !== undefined) {
resolve(api.id);
}
});
})
.then((apiId) => {
const promises = [];
if (this.custom.apigateway.responses) {
this.custom.apigateway.responses.forEach((response) => {
if (response.response.headers) {
promises.push(this.configHeaders.bind(this, apiId, response.response));
}
if (response.response.bodyMappingTemplate) {
promises.push(this.configBodyMapping.bind(this, apiId, response.response));
}
});
}
if (this.custom.apigateway.binaryTypes) {
promises.push(this.configBinary.bind(this, apiId));
}
return Promise.mapSeries(promises, fn => fn()).then(() => apiId);
})
.then((apiId) => {
this.createDeployment(apiId);
})
.then(() => this.serverless.cli.log('API Gateway Configuring: End'))
.catch((err) => {
throw err;
});
}
}
/**
* @description this is to creates a deployment resources, to make all changes effect
*
* @param apiId - the API id
* @param response
*/
createDeployment(apiId) {
return new Promise((resolve, reject) => {
this.apiGatewaySDK.createDeployment(
{
restApiId: apiId,
stageName: this.stage,
description: 'This deployment created by serverless-apigateway-plugin'
},
(error, data) => {
if (error) {
if (error.code === 'TooManyRequestsException') {
this.serverless.cli.log('Deployment failed! Retry in 5s');
setTimeout(() => {
this.createDeployment(apiId);
}, this.createDeploymentRetryDelay);
} else {
reject(error);
}
} else {
this.serverless.cli.log('Create deployment finished');
resolve('Success');
}
}
);
});
}
/**
* @description this is to configure the headers
*
* @param apiId - the API id
* @param response
*/
configHeaders(apiId, response) {
return new Promise((resolve, reject) => {
const params = {
responseType: response.type.toString(),
/* required */
restApiId: apiId,
/* required */
responseParameters: response.headers ? response.headers : {},
statusCode: response.statusCode.toString()
};
this.apiGatewaySDK.putGatewayResponse(params, (err, data) => {
if (err) {
reject(err);
} else {
this.serverless.cli.log('API Gateway Configuring: Headers are set correctly');
resolve(`Header set successfully: ${response.type.toString()}`);
}
});
});
}
/**
* @description configure the body mapping templates
*
* @param apiId
* @param response
*/
configBodyMapping(apiId, response) {
return new Promise((resolve, reject) => {
const params = {
responseType: response.type.toString(),
/* required */
restApiId: apiId,
/* required */
patchOperations: [
{
op: 'add',
path: `/responseTemplates/${response.bodyMappingTemplate.contentType.replace(
'/',
'~1'
)}`,
value: response.bodyMappingTemplate.content
}
]
};
this.apiGatewaySDK.updateGatewayResponse(params, (err, data) => {
if (err) {
reject(err);
} else {
this.serverless.cli.log(
'API Gateway Configuring: Body mapping templates are set correctly'
);
resolve(`Body Mapping Templates set successfully: ${response.type.toString()}`);
}
});
});
}
/**
* @description binary support configuration
* @param apiId
*/
configBinary(apiId) {
const patchOperationsArray = [];
this.custom.apigateway.binaryTypes.forEach((e) => {
patchOperationsArray.push({
op: 'add',
path: `/binaryMediaTypes/${e.replace('/', '~1')}`
});
});
return new Promise((resolve, reject) => {
const params = {
restApiId: apiId,
/* required */
patchOperations: patchOperationsArray
};
this.apiGatewaySDK.updateRestApi(params, (err, data) => {
if (err) {
reject(err);
} else {
this.serverless.cli.log('API Gateway Configuring: Binary support are set correctly');
resolve('binary set successfully');
}
});
});
}
}
module.exports = APIGatewayCustomiser;