forked from sid88in/serverless-appsync-plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
267 lines (242 loc) · 8.72 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
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
const fs = require('fs');
const path = require('path');
const { validateSchema, printError, parse, buildASTSchema } = require('graphql');
const getConfig = require('./get-config');
const MIGRATION_DOCS = 'https://github.com/sid88in/serverless-appsync-plugin/blob/master/README.md#cfn-migration';
class ServerlessAppsyncPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.provider = this.serverless.getProvider('aws');
this.commands = {
'delete-appsync': {
usage: 'Helps you delete AppSync API',
lifecycleEvents: ['delete'],
},
'deploy-appsync': {
usage: 'DEPRECATED: Helps you deploy AppSync API',
lifecycleEvents: ['deploy'],
},
'update-appsync': {
usage: 'DEPRECATED: Helps you update AppSync API',
lifecycleEvents: ['update'],
},
};
const generateMigrationErrorMessage = command => () => {
throw new this.serverless.classes.Error(`serverless-appsync: ${command} `
+ `is no longer supported. See ${MIGRATION_DOCS} for more information`);
};
this.hooks = {
'before:deploy:initialize': () => this.validateSchema(),
'delete-appsync:delete': () => this.deleteGraphQLEndpoint(),
'deploy-appsync:deploy': generateMigrationErrorMessage('deploy-appsync'),
'update-appsync:update': generateMigrationErrorMessage('update-appsync'),
'before:deploy:deploy': () => this.addResources(),
};
}
loadConfig() {
return getConfig(
this.serverless.service.custom.appSync,
this.serverless.service.provider,
this.serverless.config.servicePath,
);
}
getSchema() {
const { schema } = this.loadConfig();
const awsTypes = `
scalar AWSDate
scalar AWSTime
scalar AWSDateTime
scalar AWSTimestamp
scalar AWSEmail
scalar AWSJSON
scalar AWSURL
scalar AWSPhone
scalar AWSIPAddress
`;
return `${schema} ${awsTypes}`;
}
validateSchema() {
const schema = this.getSchema();
const ast = buildASTSchema(parse(schema));
const errors = validateSchema(ast);
if (!errors.length) {
return;
}
errors.forEach((error) => {
this.serverless.cli.log(printError(error));
});
throw new this.serverless.classes.Error('Cannot proceed invalid graphql SDL');
}
deleteGraphQLEndpoint() {
const config = this.loadConfig();
const { apiId } = config;
if (!apiId) {
throw new this.serverless.classes.Error('serverless-appsync: no apiId is defined. If you are not '
+ `migrating from a previous version of the plugin this is expected. See ${MIGRATION_DOCS} '
+ 'for more information`);
}
this.serverless.cli.log('Deleting GraphQL Endpoint...');
return this.provider
.request('AppSync', 'deleteGraphqlApi', {
apiId,
})
.then((data) => {
if (data) {
this.serverless.cli.log(`Successfully deleted GraphQL Endpoint: ${apiId}`);
}
});
}
addResources() {
const config = this.loadConfig();
if (config.apiId) {
this.serverless.cli.log('WARNING: serverless-appsync has been updated in a breaking way and your '
+ 'service is configured using a reference to an existing apiKey in '
+ '`custom.appSync` which is used in the legacy deploy scripts. This deploy will create '
+ `new graphql resources and WILL NOT update your existing api. See ${MIGRATION_DOCS} for `
+ 'more information');
}
const resources = this.serverless.service.provider.compiledCloudFormationTemplate.Resources;
Object.assign(resources, this.getGraphQlApiEndpointResource(config));
Object.assign(resources, this.getApiKeyResources(config));
Object.assign(resources, this.getGraphQLSchemaResource(config));
Object.assign(resources, this.getDataSourceResources(config));
Object.assign(resources, this.getResolverResources(config));
const outputs = this.serverless.service.provider.compiledCloudFormationTemplate.Outputs;
Object.assign(outputs, this.getGraphQlApiOutputs(config));
Object.assign(outputs, this.getApiKeyOutputs(config));
}
getGraphQlApiEndpointResource(config) {
return {
GraphQlApi: {
Type: 'AWS::AppSync::GraphQLApi',
Properties: {
Name: config.name,
AuthenticationType: config.authenticationType,
UserPoolConfig: config.authenticationType !== 'AMAZON_COGNITO_USER_POOLS' ? undefined : {
AwsRegion: config.region,
DefaultAction: config.userPoolConfig.defaultAction,
UserPoolId: config.userPoolConfig.userPoolId,
},
OpenIDConnectConfig: config.authenticationType !== 'OPENID_CONNECT' ? undefined : {
Issuer: config.openIdConnectConfig.issuer,
ClientId: config.openIdConnectConfig.clientId,
IatTTL: config.openIdConnectConfig.iatTTL,
AuthTTL: config.openIdConnectConfig.authTTL,
},
LogConfig: !config.logConfig ? undefined : {
CloudWatchLogsRoleArn: config.logConfig.loggingRoleArn,
FieldLogLevel: config.logConfig.level,
},
},
},
};
}
getApiKeyResources(config) {
if (config.authenticationType !== 'API_KEY') {
return {};
}
return {
GraphQlApiKeyDefault: {
Type: 'AWS::AppSync::ApiKey',
Properties: {
ApiId: { 'Fn::GetAtt': ['GraphQlApi', 'ApiId'] },
Description: 'serverless-appsync-plugin: Default',
Expires: Math.floor(Date.now() / 1000) + (365 * 24 * 60 * 60),
},
},
};
}
getDataSourceResources(config) {
return config.dataSources.reduce((acc, ds) => {
const resource = {
Type: 'AWS::AppSync::DataSource',
Properties: {
ApiId: { 'Fn::GetAtt': ['GraphQlApi', 'ApiId'] },
Name: ds.name,
Description: ds.description,
Type: ds.type,
ServiceRoleArn: ds.type === 'NONE' ? undefined : ds.config.serviceRoleArn,
},
};
if (ds.type === 'AWS_LAMBDA') {
resource.Properties.LambdaConfig = {
LambdaFunctionArn: ds.config.lambdaFunctionArn,
};
} else if (ds.type === 'AMAZON_DYNAMODB') {
resource.Properties.DynamoDBConfig = {
AwsRegion: ds.config.region || config.region,
TableName: ds.config.tableName,
UseCallerCredentials: !!ds.config.useCallerCredentials,
};
} else if (ds.type === 'AMAZON_ELASTICSEARCH') {
resource.Properties.ElasticsearchConfig = {
AwsRegion:ds.config.region || config.region,
Endpoint: ds.config.endpoint,
};
} else if (ds.type === 'HTTP') {
resource.Properties.HttpConfig = {
Endpoint: ds.config.endpoint,
};
} else if (ds.type !== 'NONE') {
throw new this.serverless.classes.Error(`Data Source Type not supported: '${ds.type}`);
}
return Object.assign({}, acc, { [this.getDataSourceCfnName(ds.name)]: resource });
}, {});
}
getGraphQLSchemaResource(config) {
return {
GraphQlSchema: {
Type: 'AWS::AppSync::GraphQLSchema',
Properties: {
Definition: config.schema,
ApiId: { 'Fn::GetAtt': ['GraphQlApi', 'ApiId'] },
},
},
};
}
getResolverResources(config) {
return config.mappingTemplates.reduce((acc, tpl) => {
const reqTemplPath = path.join(config.mappingTemplatesLocation, tpl.request);
const respTemplPath = path.join(config.mappingTemplatesLocation, tpl.response);
return Object.assign({}, acc, {
[`GraphQlResolver${this.getCfnName(tpl.type)}${this.getCfnName(tpl.field)}`]: {
Type: 'AWS::AppSync::Resolver',
DependsOn: 'GraphQlSchema',
Properties: {
ApiId: { 'Fn::GetAtt': ['GraphQlApi', 'ApiId'] },
TypeName: tpl.type,
FieldName: tpl.field,
DataSourceName: { 'Fn::GetAtt': [this.getDataSourceCfnName(tpl.dataSource), 'Name'] },
RequestMappingTemplate: fs.readFileSync(reqTemplPath, 'utf8'),
ResponseMappingTemplate: fs.readFileSync(respTemplPath, 'utf8'),
},
},
});
}, {});
}
getGraphQlApiOutputs() {
return {
GraphQlApiUrl: {
Value: { 'Fn::GetAtt': ['GraphQlApi', 'GraphQLUrl'] },
},
};
}
getApiKeyOutputs(config) {
if (config.authenticationType !== 'API_KEY') {
return {};
}
return {
GraphQlApiKeyDefault: {
Value: { 'Fn::GetAtt': ['GraphQlApiKeyDefault', 'ApiKey'] },
},
};
}
getCfnName(name) {
return name.replace(/[^a-zA-Z0-9]/g, '');
}
getDataSourceCfnName(name) {
return `GraphQlDs${this.getCfnName(name)}`;
}
}
module.exports = ServerlessAppsyncPlugin;