forked from alexdebrie/serverless-endpoint-configuration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
105 lines (93 loc) · 2.83 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
'use strict';
class ServerlessPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.provider = this.serverless.getProvider('aws');
this.commands = {
endpoints: {
commands: {
set: {
usage: 'Sets your endpoint configuration to the desired type',
lifecycleEvents: [
'set',
]
},
},
},
};
this.hooks = {
'endpoints:set:set': this.setEndpointType.bind(this),
'before:aws:deploy:finalize:cleanup': this.updateAfterDeploy.bind(this)
};
}
validate() {
if (!this.serverless.service.custom || !this.serverless.service.custom.endpoint || !this.serverless.service.custom.endpoint.type) {
throw new Error("Must include 'type' parameter in 'endpoint' section of 'custom' block.")
}
this.endpointType = this.serverless.service.custom.endpoint.type.toUpperCase();
if (['REGIONAL', 'EDGE'].indexOf(this.endpointType) == -1 ) {
throw new Error(`Endpoint type is ${this.endpointType}. Must be REGIONAL or EDGE`);
}
}
shouldUpdateOnDeploy() {
if (this.serverless.service.custom && this.serverless.service.custom.endpoint && this.serverless.service.custom.endpoint.updateOnDeploy === false ) {
return false;
};
return true;
}
updateAfterDeploy() {
if (!this.shouldUpdateOnDeploy() ) {
return
}
this.setEndpointType();
}
setEndpointType() {
this.validate();
this.getRestApi()
.then((restApi) => {
const restApiId = restApi.PhysicalResourceId;
return this.setEndpointTypeForRestApi(restApiId);
}).then(() => {
this.serverless.cli.log(`Endpoint configuration set to ${this.endpointType}`);
}).catch((err) => {
throw new Error(err);
});
}
getRestApi() {
const stackName = this.provider.naming.getStackName(this.options.stage);
const stackResourcesPromise = this.provider.request('CloudFormation',
'listStackResources',
{ StackName: stackName },
this.options.stage,
this.options.region);
return stackResourcesPromise
.then((data) => {
const restApis = data.StackResourceSummaries
.filter((resource) => {
return resource.ResourceType == 'AWS::ApiGateway::RestApi';
})
if (restApis) {
return restApis[0];
}
})
throw new Error('Could not find RestApi in service');
}
setEndpointTypeForRestApi(restApiId) {
const params = {
restApiId,
patchOperations: [
{
op: 'replace',
path: "/endpointConfiguration/types/EDGE",
value: this.endpointType
}
]
};
return this.provider.request('APIGateway',
'updateRestApi',
params
)
}
}
module.exports = ServerlessPlugin;