-
Notifications
You must be signed in to change notification settings - Fork 1
/
schema.js
453 lines (419 loc) · 12.3 KB
/
schema.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
const {
makeExecutableSchema,
SchemaDirectiveVisitor,
} = require('graphql-tools');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const json5 = require('json5');
const { GraphQLError } = require('graphql');
const { create: createUtils, getAppSyncConfig } = require('./util');
const { javaify, vtl } = require('./vtl');
const dynamodbSource = require('./dynamodbSource');
const lambdaSource = require('./lambdaSource');
const httpSource = require('./httpSource');
const elasticsearchSource = require('./elasticsearchSource');
const log = require('logdown')('appsync-emulator:schema');
const consola = require('./log');
const { inspect } = require('util');
const { scalars } = require('./schemaWrapper');
const DataLoader = require('dataloader');
const vtlMacros = {
console: (...args) => {
// eslint-disable-next-line no-console
console.log(...args);
return '';
},
};
// eslint-disable-next-line
const gqlPathAsArray = path => {
const flattened = [];
let curr = path;
while (curr) {
flattened.push(curr.key);
curr = curr.prev;
}
return flattened.reverse();
};
class AppSyncError extends Error {
constructor(errors = []) {
super('aggregate errors');
this.errors = errors;
}
}
// eslint-disable-next-line
const buildVTLContext = ({ root, vars, context, info }, result = null, stash = null) => {
const {
jwt: { iss: issuer, sub },
request,
} = context;
const util = createUtils();
const args = javaify(vars);
const vtlRequest = request ? { headers: request.headers } : {};
const vtlContext = {
arguments: args,
args,
request: vtlRequest,
identity: javaify({
sub,
issuer,
username: context.jwt['cognito:username'],
sourceIp: ['0.0.0.0'],
defaultAuthStrategy: 'ALLOW',
claims: context.jwt,
}),
source: root || {},
result: javaify(result),
stash: stash || javaify({}),
};
return {
util,
utils: util,
context: vtlContext,
ctx: vtlContext,
};
};
const returnJSON = input => {
try {
// apparently appsync allows things like trailing commas.
return json5.parse(input);
} catch (err) {
consola.error(
new Error('Failed to parse VTL template as JSON (see below)'),
);
consola.error(input);
throw err;
}
};
const handleVTLRender = (
str,
context,
// eslint-disable-next-line
vtlMacros,
{ info: gqlInfo, context: gqlContext },
) => {
let templateOutput;
try {
templateOutput = vtl(str.toString(), context, vtlMacros);
} catch (err) {
// only throw the template parsing error if we have not
// set an error on context. This will ensure we abort the template
// but return the correct error message.
if (context.util.getErrors().length === 0) {
throw err;
}
}
// check if we have any errors.
const errors = context.util.getErrors();
if (!errors.length) {
return returnJSON(templateOutput);
}
// eslint-disable-next-line
gqlContext.appsyncErrors = errors.map(error => {
// XXX: Note we use a field other than "message" as it gets mutated
// by the velocity engine breaking this logic.
const { gqlMessage: message, errorType, data, errorInfo } = error;
const gqlErrorObj = new GraphQLError(
message,
gqlInfo.fieldNodes,
null,
null,
gqlPathAsArray(gqlInfo.path),
);
Object.assign(gqlErrorObj, { errorType, data, errorInfo });
return gqlErrorObj;
});
log.error('GraphQL Errors', gqlContext.appsyncErrors);
throw gqlContext.appsyncErrors[0];
};
const runRequestVTL = (fullPath, graphqlInfo) => {
log.info('loading request vtl', path.relative(process.cwd(), fullPath));
const context = buildVTLContext(graphqlInfo);
const content = fs.readFileSync(fullPath, 'utf8');
return [
handleVTLRender(content.toString(), context, vtlMacros, graphqlInfo),
context.ctx.stash,
];
};
const runResponseVTL = (fullPath, graphqlInfo, result, stash) => {
log.info('loading response vtl', path.relative(process.cwd(), fullPath));
const context = buildVTLContext(graphqlInfo, result, stash);
const content = fs.readFileSync(fullPath, 'utf8');
return handleVTLRender(content.toString(), context, vtlMacros, graphqlInfo);
};
const dispatchRequestToSource = async (
source,
{ dynamodb, dynamodbTables, serverlessDirectory, serverlessConfig },
request,
) => {
consola.info(
'Dispatch to source',
inspect({ name: source.name, type: source.type }),
);
log.info('resolving with source: ', source.name, source.type);
switch (source.type) {
case 'AMAZON_DYNAMODB':
return dynamodbSource(
dynamodb,
// default alias
source.config.tableName,
// mapping used for multi table operations.
dynamodbTables,
request,
);
case 'AWS_LAMBDA':
return lambdaSource(
{
serverlessDirectory,
serverlessConfig,
dynamodbEndpoint: dynamodb.endpoint.href,
dynamodbTables,
},
source.config.functionName,
request,
);
case 'AMAZON_ELASTICSEARCH':
return elasticsearchSource(source.config.endpoint, request);
case 'HTTP':
return httpSource(source.config.endpoint, request);
case 'NONE':
return request.payload;
default:
throw new Error(`Cannot handle source type: ${source.type}`);
}
};
const generateDataLoaderResolver = (source, configs) => {
const batchLoaders = {};
return fieldPath => {
if (batchLoaders[fieldPath] === undefined) {
batchLoaders[fieldPath] = new DataLoader(
requests => {
const batchRequest = requests[0];
batchRequest.payload = requests.map(r => r.payload);
consola.info(
'Rendered Batch Request:\n',
inspect(batchRequest, { depth: null, colors: true }),
);
log.info('resolver batch request', batchRequest);
return dispatchRequestToSource(source, configs, batchRequest);
},
{
shouldCache: false,
},
);
}
return batchLoaders[fieldPath];
};
};
const generateTypeResolver = (
source,
configs,
{ requestPath, responsePath, dataLoaderResolver },
) => async (root, vars, context, info) => {
try {
const fieldPath = `${info.parentType}.${info.fieldName}`;
const pathInfo = gqlPathAsArray(info.path);
consola.start(`Resolve: ${fieldPath} [${pathInfo}]`);
log.info('resolving', pathInfo);
assert(context && context.jwt, 'must have context.jwt');
const resolverArgs = { root, vars, context, info };
const [request, stash] = runRequestVTL(requestPath, resolverArgs);
let requestResult;
if (request.operation === 'BatchInvoke') {
const loader = dataLoaderResolver(fieldPath);
requestResult = await loader.load(request);
} else {
consola.info(
'Rendered Request:\n',
inspect(request, { depth: null, colors: true }),
);
log.info('resolver request', request);
requestResult = await dispatchRequestToSource(source, configs, request);
}
const response = runResponseVTL(
responsePath,
resolverArgs,
requestResult,
stash,
);
consola.info(
'Rendered Response:\n',
inspect(response, { depth: null, colors: true }),
);
log.info('resolver response', response);
// XXX: parentType probably is constructed with new String so == is required.
// eslint-disable-next-line
if (info.parentType == 'Mutation') {
configs.pubsub.publish(info.fieldName, response);
}
return response;
} catch (err) {
consola.error(`${info.parentType}.${info.fieldName} failed`);
consola.error(err.errorMessage || err.stack || err);
throw err;
}
};
const generateSubscriptionTypeResolver = (
field,
source,
configs,
{ requestPath, responsePath },
) => {
const subscriptionList = configs.subscriptions[field];
if (!subscriptionList) {
// no subscriptions found.
return () => {};
}
const { mutations } = subscriptionList;
assert(
mutations && mutations.length,
`${field} must have aws_subscribe with mutations arg`,
);
return {
resolve: async (root, _, context, info) => {
consola.start(
`Resolve: ${info.parentType}.${info.fieldName} [${gqlPathAsArray(
info.path,
)}]`,
);
log.info('resolving', gqlPathAsArray(info.path));
assert(context && context.jwt, 'must have context.jwt');
// XXX: The below is what our templates expect but not 100% sure it's correct.
// for subscriptions the "arguments" field is same as root here.
const resolverArgs = { root, vars: root, context, info };
const [request, stash] = runRequestVTL(requestPath, resolverArgs);
const requestResult =
(await dispatchRequestToSource(source, configs, request)) || {};
consola.info(
'Rendered Request:\n',
inspect(requestResult, { depth: null, colors: true }),
);
log.info('subscription resolver request', requestResult);
const response = runResponseVTL(
responsePath,
resolverArgs,
requestResult,
stash,
);
consola.info(
'Rendered Response:\n',
inspect(response, { depth: null, colors: true }),
);
log.info('subscription resolver response', response);
return response;
},
subscribe() {
return configs.pubsub.asyncIterator(mutations);
},
};
};
const generateResolvers = (cwd, config, configs) => {
const { mappingTemplatesLocation = 'mapping-templates' } = config;
const mappingTemplates = path.join(cwd, mappingTemplatesLocation);
const dataSourceByName = config.dataSources.reduce(
(sum, value) => ({
...sum,
[value.name]: value,
}),
{},
);
return config.mappingTemplates.reduce(
(sum, { dataSource, type, field, request, response }) => {
if (!sum[type]) {
// eslint-disable-next-line
sum[type] = {};
}
const source = dataSourceByName[dataSource];
const pathing = {
requestPath: path.join(mappingTemplates, request),
dataLoaderResolver: generateDataLoaderResolver(source, configs),
responsePath: path.join(mappingTemplates, response),
};
const resolver =
type === 'Subscription'
? generateSubscriptionTypeResolver(field, source, configs, pathing)
: generateTypeResolver(source, configs, pathing);
return {
...sum,
[type]: {
...sum[type],
[field]: resolver,
},
};
},
{ ...scalars },
);
};
const createSubscriptionsVisitor = () => {
const subscriptions = {};
class DirectiveVisitor extends SchemaDirectiveVisitor {
visitFieldDefinition(field) {
subscriptions[field.name] = this.args;
}
}
return {
subscriptions,
DirectiveVisitor,
};
};
const createSchema = async ({
dynamodb,
dynamodbTables,
graphqlSchema,
serverlessDirectory,
serverlessConfig,
pubsub,
} = {}) => {
assert(dynamodb, 'must pass dynamodb');
assert(
dynamodbTables && typeof dynamodbTables === 'object',
'must pass dynamodbTables',
);
assert(graphqlSchema, 'must pass graphql schema');
assert(serverlessDirectory, 'must pass serverless dir');
assert(serverlessConfig, 'must pass serverless config');
assert(pubsub, 'must pass pubsub');
const { subscriptions, DirectiveVisitor } = createSubscriptionsVisitor();
const appSyncConfig = getAppSyncConfig(serverlessConfig);
// XXX: Below is a nice and easy hack.
// walk the AST without saving the schema ... this is to capture subscription directives.
makeExecutableSchema({
typeDefs: graphqlSchema,
schemaDirectives: {
aws_subscribe: DirectiveVisitor,
},
});
const resolvers = await generateResolvers(
serverlessDirectory,
appSyncConfig,
{
dynamodb,
dynamodbTables,
pubsub,
subscriptions,
serverlessDirectory,
serverlessConfig,
},
);
const schema = makeExecutableSchema({
typeDefs: graphqlSchema,
resolvers,
schemaDirectives: {
aws_subscribe: DirectiveVisitor,
},
});
const topics = Array.from(
new Set(
Object.values(subscriptions).reduce(
(sum, { mutations }) => sum.concat(mutations),
[],
),
),
);
return {
schema,
topics,
subscriptions,
};
};
module.exports = { createSchema, AppSyncError };