-
Notifications
You must be signed in to change notification settings - Fork 152
/
merge.ts
630 lines (563 loc) · 17.2 KB
/
merge.ts
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
import { Api, DataSource, StaticApiCustom } from './index';
import {
ASTNode,
buildSchema,
GraphQLSchema,
Kind,
ObjectTypeDefinitionNode,
parse,
print,
printSchema,
visit,
} from 'graphql';
import { mergeSchemas } from '@graphql-tools/schema';
import {
ConfigurationVariableKind,
DataSourceKind,
FieldConfiguration,
TypeConfiguration,
} from '@wundergraph/protobuf';
export const mergeApis = <T extends {} = {}>(roles: string[], ...apis: Api<T>[]): Api<T> => {
const dataSources: DataSource<T>[] = apis
.map((api) => api.DataSources || [])
.reduce((previousValue, currentValue) => [...previousValue, ...currentValue], []);
const fields = mergeApiFields(apis);
const types = mergeTypeConfigurations(apis);
const schema = mergeApiSchemas(roles, apis, dataSources, fields);
const interpolateVariableDefinitionAsJSON = apis.flatMap((api) => api.interpolateVariableDefinitionAsJSON);
return new Api(schema, dataSources, fields, types, interpolateVariableDefinitionAsJSON);
};
const mergeApiFields = <T extends {} = {}>(apis: Api<T>[]): FieldConfiguration[] => {
const fields: FieldConfiguration[] = [];
apis
.map((a) => a.Fields || [])
.reduce((previousValue, currentValue) => [...previousValue, ...currentValue], [])
.forEach((f) => {
const existing = fields.find(
(existing) => existing.typeName === f.typeName && existing.fieldName === f.fieldName
);
if (!existing) {
fields.push(f);
return;
}
if (f.requiresFields) {
existing.requiresFields = [...new Set([...(existing.requiresFields || []), ...f.requiresFields])];
}
if (f.argumentsConfiguration) {
existing.argumentsConfiguration = existing.argumentsConfiguration || [];
f.argumentsConfiguration.forEach((a) => {
const exists = existing.argumentsConfiguration!.find((e) => e.name === a.name) !== undefined;
if (exists) {
return;
}
existing.argumentsConfiguration!.push(a);
});
}
});
return fields;
};
const mergeTypeConfigurations = <T extends {} = {}>(apis: Api<T>[]): TypeConfiguration[] => {
const out: TypeConfiguration[] = [];
apis
.map((api) => api.Types || [])
.forEach((types) =>
types.forEach((conf) => {
const exists = out.find((existing) => existing.typeName === conf.typeName) !== undefined;
if (exists) {
return;
}
out.push(conf);
})
);
return out;
};
export const baseSchema = `
directive @fromClaim(
name: Claim
) on VARIABLE_DEFINITION
"""
The @removeNullVariables directive allows you to remove variables with null value from your GraphQL Query or Mutation Operations.
A potential use-case could be that you have a graphql upstream which is not accepting null values for variables.
By enabling this directive all variables with null values will be removed from upstream query.
query ($say: String, $name: String) @removeNullVariables {
hello(say: $say, name: $name)
}
Directive will transform variables json and remove top level null values.
{ "say": null, "name": "world" }
So upstream will receive the following variables:
{ "name": "world" }
"""
directive @removeNullVariables on QUERY | MUTATION
enum Claim {
USERID
EMAIL
EMAIL_VERIFIED
NAME
NICKNAME
LOCATION
PROVIDER
}
directive @hooksVariable on VARIABLE_DEFINITION
directive @jsonSchema (
"""
The value of both of these keywords MUST be a string.
Both of these keywords can be used to decorate a user interface with
information about the data produced by this user interface. A title
will preferably be short, whereas a description will provide
explanation about the purpose of the instance described by this
schema.
"""
title: String
"""
The value of both of these keywords MUST be a string.
Both of these keywords can be used to decorate a user interface with
information about the data produced by this user interface. A title
will preferably be short, whereas a description will provide
explanation about the purpose of the instance described by this
schema.
"""
description: String
"""
The value of "multipleOf" MUST be a number, strictly greater than 0.
A numeric instance is valid only if division by this keyword's value
results in an integer.
"""
multipleOf: Int
"""
The value of "maximum" MUST be a number, representing an inclusive
upper limit for a numeric instance.
If the instance is a number, then this keyword validates only if the
instance is less than or exactly equal to "maximum".
"""
maximum: Int
"""
The value of "exclusiveMaximum" MUST be number, representing an
exclusive upper limit for a numeric instance.
If the instance is a number, then the instance is valid only if it
has a value strictly less than (not equal to) "exclusiveMaximum".
"""
exclusiveMaximum: Int
"""
The value of "minimum" MUST be a number, representing an inclusive
lower limit for a numeric instance.
If the instance is a number, then this keyword validates only if the
instance is greater than or exactly equal to "minimum".
"""
minimum: Int
"""
The value of "exclusiveMinimum" MUST be number, representing an
exclusive lower limit for a numeric instance.
If the instance is a number, then the instance is valid only if it
has a value strictly greater than (not equal to) "exclusiveMinimum".
"""
exclusiveMinimum: Int
"""
The value of this keyword MUST be a non-negative integer.
A string instance is valid against this keyword if its length is less
than, or equal to, the value of this keyword.
The length of a string instance is defined as the number of its
characters as defined by RFC 7159 [RFC7159].
"""
maxLength: Int
"""
The value of this keyword MUST be a non-negative integer.
A string instance is valid against this keyword if its length is
greater than, or equal to, the value of this keyword.
The length of a string instance is defined as the number of its
characters as defined by RFC 7159 [RFC7159].
Omitting this keyword has the same behavior as a value of 0.
"""
minLength: Int
"""
The value of this keyword MUST be a string. This string SHOULD be a
valid regular expression, according to the ECMA 262 regular
expression dialect.
A string instance is considered valid if the regular expression
matches the instance successfully. Recall: regular expressions are
not implicitly anchored.
"""
pattern: String
"""
The value of this keyword MUST be a non-negative integer.
An array instance is valid against "maxItems" if its size is less
than, or equal to, the value of this keyword.
"""
maxItems: Int
"""
The value of this keyword MUST be a non-negative integer.
An array instance is valid against "minItems" if its size is greater
than, or equal to, the value of this keyword.
Omitting this keyword has the same behavior as a value of 0.
"""
minItems: Int
"""
The value of this keyword MUST be a boolean.
If this keyword has boolean value false, the instance validates
successfully. If it has boolean value true, the instance validates
successfully if all of its elements are unique.
Omitting this keyword has the same behavior as a value of false.
"""
uniqueItems: Boolean
commonPattern: COMMON_REGEX_PATTERN
) on VARIABLE_DEFINITION
enum COMMON_REGEX_PATTERN {
EMAIL
DOMAIN
}
`;
const roleSchema = (roles: string[]) => `
directive @rbac(
"the user must match all roles"
requireMatchAll: [WG_ROLE]
"the user must match at least one of the roles"
requireMatchAny: [WG_ROLE]
"the user must not match all of the roles"
denyMatchAll: [WG_ROLE]
"the user must not match any of the roles"
denyMatchAny: [WG_ROLE]
) on QUERY | MUTATION | SUBSCRIPTION
enum WG_ROLE {
${roles.join(' ')}
}
`;
const uuidSchema = `
"""
The directive @injectGeneratedUUID injects a generated UUID into the variable.
This variable MUST be a string.
At the same time, it removes the variable from the input definition,
disallowing the user to supply it.
This means, the UUID is 100% generated server-side and can be considered untempered.
"""
directive @injectGeneratedUUID on VARIABLE_DEFINITION
`;
const injectEnvironmentVariableSchema = `
"""
The directive @injectEnvironmentVariable allows you to inject an environment variable into the variable definition.
"""
directive @injectEnvironmentVariable (
name: String!
) on VARIABLE_DEFINITION
`;
const dateTimeSchema = `
"""
The directive @injectCurrentDateTime injects a DateTime string of the current date and time into the variable.
This variable MUST be a string compatible scalar.
The default format, is: ISO 8601
If no format is chosen, the default format is used.
Custom formats are allowed by specifying a format conforming to the Golang specification for specifying a date time format.
"""
directive @injectCurrentDateTime (
format: WunderGraphDateTimeFormat = ISO8601
"""customFormat must conform to the Golang specification for specifying a date time format"""
customFormat: String
) on VARIABLE_DEFINITION
enum WunderGraphDateTimeFormat {
"2006-01-02T15:04:05-0700"
ISO8601
"Mon Jan _2 15:04:05 2006"
ANSIC
"Mon Jan _2 15:04:05 MST 2006"
UnixDate
"Mon Jan 02 15:04:05 -0700 2006"
RubyDate
"02 Jan 06 15:04 MST"
RFC822
"02 Jan 06 15:04 -0700"
RFC822Z
"Monday, 02-Jan-06 15:04:05 MST"
RFC850
"Mon, 02 Jan 2006 15:04:05 MST"
RFC1123
"Mon, 02 Jan 2006 15:04:05 -0700"
RFC1123Z
"2006-01-02T15:04:05Z07:00"
RFC3339
"2006-01-02T15:04:05.999999999Z07:00"
RFC3339Nano
"3:04PM"
Kitchen
"Jan _2 15:04:05"
Stamp
"Jan _2 15:04:05.000"
StampMilli
"Jan _2 15:04:05.000000"
StampMicro
"Jan _2 15:04:05.000000000"
StampNano
}
`;
const internalSchema = `
"""
The @internalOperation Directive marks an Operation as internal.
By doing so, the Operation is no longer accessible from the public API.
It can only be accessed by internal services, like hooks.
"""
directive @internalOperation on QUERY | MUTATION | SUBSCRIPTION
`;
const exportSchema = `
"""
The @export directive instructs the Execution Planner to export the field during the execution into the variable of the 'as' argument.
As the execution is depth first, a field can only be used after it has been exported.
Additionally, a field can only be used after using the '_join' field or on a different data source.
It's not possible to export a field and use it in for the same data source.
Note that the @export directive only works on fields that return a single value.
It's not possible to export a list or object field.
"""
directive @export (
"""
The argument 'as' is the name of the variable to export the field to.
"""
as: String!
) on FIELD
"""
The directive @internal marks a variable definition as internal so that clients can't access it.
The field is also not visible in the public API.
It's only being used as an internal variable to export fields into.
"""
directive @internal on VARIABLE_DEFINITION
`;
const transformSchema = `
"""
The @transform directive allows to apply transformations to the response.
By applying the directive, the shape of the response can be altered,
which will also modify the JSON-Schema of the response.
That is, you will keep full type safety and code-generation for transformed fields.
"""
directive @transform(
"""
Using the 'get' transformation allows you to extract a nested field using a JSON path.
This is useful to unnest data, e.g. when using the '_join' field, which adds an extra layer of nesting.
Example:
query GetName {
name: me @transform(get: "info.name") {
info {
name
}
}
}
Before the transformation, the resolve looks like this:
{
"name": {
"info": {
"name": "John Doe"
}
}
}
With the transformation applied, the response will be reshaped like this:
{
"name": "John Doe"
}
"""
get: String
) on FIELD
`;
const mergeApiSchemas = <T extends {} = {}>(
roles: string[],
apis: Api<T>[],
dataSources: DataSource[],
fields: FieldConfiguration[]
): string => {
const graphQLSchemas = apis
.map((api, i) => {
return api.Schema
? buildSchema(api.Schema, {
assumeValidSDL: true,
})
: null;
})
.flatMap((schema) => (schema ? [schema] : []));
graphQLSchemas.push(
buildSchema(baseSchema, {
assumeValidSDL: true,
})
);
if (roles.length) {
graphQLSchemas.push(buildSchema(roleSchema(roles), { assumeValidSDL: true }));
}
graphQLSchemas.push(buildSchema(dateTimeSchema, { assumeValidSDL: true }));
graphQLSchemas.push(buildSchema(uuidSchema, { assumeValidSDL: true }));
graphQLSchemas.push(buildSchema(internalSchema, { assumeValidSDL: true }));
graphQLSchemas.push(buildSchema(injectEnvironmentVariableSchema, { assumeValidSDL: true }));
graphQLSchemas.push(buildSchema(exportSchema, { assumeValidSDL: true }));
graphQLSchemas.push(buildSchema(transformSchema, { assumeValidSDL: true }));
let mergedGraphQLSchema: GraphQLSchema;
try {
mergedGraphQLSchema = mergeSchemas({
schemas: graphQLSchemas,
assumeValid: true,
});
} catch (e: any) {
throw new Error(
`Schemas could not be merged. Define namespaces on the APIs to avoid type collisions. Error: ${e.message}`
);
}
const queryTypeName = mergedGraphQLSchema.getQueryType()?.name;
const mutationTypeName = mergedGraphQLSchema.getMutationType()?.name;
const subscriptionTypeName = mergedGraphQLSchema.getSubscriptionType()?.name;
const hasQueryType = queryTypeName !== undefined;
const rootTypeNames: string[] = [];
if (queryTypeName) {
rootTypeNames.push(queryTypeName);
}
if (mutationTypeName) {
rootTypeNames.push(mutationTypeName);
}
if (subscriptionTypeName) {
rootTypeNames.push(subscriptionTypeName);
}
const printed = printSchema(mergedGraphQLSchema);
const ast = parse(printed);
const filtered = visit(ast, {
ObjectTypeDefinition: (node) => {
if (node.name.value.startsWith('__')) {
return null;
}
switch (node.name.value) {
case 'Entity':
return null;
}
const hasJoinField = node.fields?.find((field) => field.name.value === '_join') !== undefined;
const isRootType = rootTypeNames.includes(node.name.value);
if (hasJoinField || isRootType || !hasQueryType) {
return;
}
const custom: StaticApiCustom = {
data: {
kind: ConfigurationVariableKind.STATIC_CONFIGURATION_VARIABLE,
staticVariableContent: '{}',
placeholderVariableName: '',
environmentVariableDefaultValue: '',
environmentVariableName: '',
},
};
dataSources.push({
Kind: DataSourceKind.STATIC,
RootNodes: [
{
typeName: node.name.value,
fieldNames: ['_join'],
},
],
Custom: custom,
ChildNodes: [],
Directives: [],
RequestTimeoutSeconds: 0,
});
fields.push({
typeName: node.name.value,
fieldName: '_join',
disableDefaultFieldMapping: true,
path: ['_join'],
requiresFields: [],
argumentsConfiguration: [],
unescapeResponseJson: false,
});
const updated: ObjectTypeDefinitionNode = {
...node,
fields: [
...(node.fields || []),
{
kind: Kind.FIELD_DEFINITION,
type: {
kind: Kind.NON_NULL_TYPE,
type: {
kind: Kind.NAMED_TYPE,
name: {
kind: Kind.NAME,
value: queryTypeName,
},
},
},
name: {
kind: Kind.NAME,
value: '_join',
},
},
],
};
return updated;
},
UnionTypeDefinition: (node) => {
if (node.name.value.startsWith('__')) {
return null;
}
},
ScalarTypeDefinition: (node) => {
if (node.name.value.startsWith('__')) {
return null;
}
},
FieldDefinition: (node) => {
if (node.name.value.startsWith('__')) {
return null;
}
},
DirectiveDefinition: (node) => {
switch (node.name.value) {
case 'key':
case 'extends':
case 'external':
case 'requires':
case 'provides':
return null;
}
},
});
const withoutEmptyDescription = removeEmptyDescriptions(filtered);
return print(withoutEmptyDescription);
};
const removeEmptyDescriptions = (astNode: ASTNode): ASTNode => {
return visit(astNode, {
enter: (node) => {
switch (node.kind) {
case 'ObjectTypeDefinition':
case 'ScalarTypeDefinition':
case 'InterfaceTypeDefinition':
case 'UnionTypeDefinition':
case 'FieldDefinition':
if (node.description && node.description.value === '') {
return {
...node,
description: undefined,
};
}
}
},
});
};
const wunderGraphDirectives = [
'internalOperation',
'injectEnvironmentVariable',
'fromClaim',
'hooksVariable',
'jsonSchema',
'rbac',
'injectGeneratedUUID',
'injectCurrentDateTime',
'internalOperation',
'export',
];
const wunderGraphEnums = ['Claim', 'COMMON_REGEX_PATTERN', 'WG_ROLE', 'WunderGraphDateTimeFormat'];
export const removeBaseSchema = (schema: string): string => {
const document = parse(schema);
const filtered = visit(document, {
ObjectTypeDefinition: (node) => {
const fields = node.fields?.filter((field) => field.name.value !== '_join');
return {
...node,
fields,
};
},
DirectiveDefinition: (node) => {
if (wunderGraphDirectives.includes(node.name.value)) {
return null;
}
},
EnumTypeDefinition: (node) => {
if (wunderGraphEnums.includes(node.name.value)) {
return null;
}
},
});
return print(filtered);
};