This repository has been archived by the owner on Oct 2, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathgenerator.dart
403 lines (346 loc) · 12.4 KB
/
generator.dart
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
// @dart = 2.8
import 'package:artemis/generator/data/data.dart';
import 'package:artemis/generator/data/enum_value_definition.dart';
import 'package:artemis/visitor/canonical_visitor.dart';
import 'package:artemis/visitor/generator_visitor.dart';
import 'package:artemis/visitor/object_type_definition_visitor.dart';
import 'package:artemis/visitor/schema_definition_visitor.dart';
import 'package:artemis/visitor/type_definition_node_visitor.dart';
import 'package:gql/ast.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as p;
import './generator/ephemeral_data.dart';
import './generator/errors.dart';
import './generator/graphql_helpers.dart' as gql;
import './generator/helpers.dart';
import './schema/options.dart';
typedef _OnNewClassFoundCallback = void Function(Context context);
/// Enum value for values not mapped in the GraphQL enum
final EnumValueDefinition ARTEMIS_UNKNOWN = EnumValueDefinition(
name: EnumValueName(name: 'ARTEMIS_UNKNOWN'),
);
/// Generate queries definitions from a GraphQL schema and a list of queries,
/// given Artemis options and schema mappings.
LibraryDefinition generateLibrary(
String path,
List<DocumentNode> gqlDocs,
GeneratorOptions options,
SchemaMap schemaMap,
List<FragmentDefinitionNode> fragmentsCommon,
DocumentNode schema,
) {
final canonicalVisitor = CanonicalVisitor(
context: Context(
schema: schema,
options: options,
schemaMap: schemaMap,
path: [],
currentType: null,
currentFieldName: null,
currentClassName: null,
generatedClasses: [],
inputsClasses: [],
fragments: [],
usedEnums: {},
usedInputObjects: {},
),
);
schema.accept(canonicalVisitor);
final queryDefinitions = gqlDocs
.map((doc) => generateDefinitions(
schema,
path,
doc,
options,
schemaMap,
fragmentsCommon,
canonicalVisitor,
))
.expand((e) => e)
.toList();
final allClassesNames = queryDefinitions
.map((def) => def.classes.map((c) => c))
.expand((e) => e)
.toList();
allClassesNames.mergeDuplicatesBy((a) => a.name, (a, b) {
if (a.name == b.name && a != b) {
throw DuplicatedClassesException(a, b);
}
return a;
});
final basename = p.basenameWithoutExtension(path);
final customImports = _extractCustomImports(schema, options);
return LibraryDefinition(
basename: basename,
queries: queryDefinitions,
customImports: customImports,
);
}
Set<FragmentDefinitionNode> _extractFragments(SelectionSetNode selectionSet,
List<FragmentDefinitionNode> fragmentsCommon) {
final result = <FragmentDefinitionNode>{};
if (selectionSet != null) {
selectionSet.selections.whereType<FieldNode>().forEach((selection) {
result.addAll(_extractFragments(selection.selectionSet, fragmentsCommon));
});
selectionSet.selections
.whereType<InlineFragmentNode>()
.forEach((selection) {
result.addAll(_extractFragments(selection.selectionSet, fragmentsCommon));
});
selectionSet.selections
.whereType<FragmentSpreadNode>()
.forEach((selection) {
final fragmentDefinitions = fragmentsCommon.firstWhere(
(fragmentDefinition) =>
fragmentDefinition.name.value == selection.name.value);
result.add(fragmentDefinitions);
result.addAll(
_extractFragments(fragmentDefinitions.selectionSet, fragmentsCommon));
});
}
return result;
}
/// Generate a query definition from a GraphQL schema and a query, given
/// Artemis options and schema mappings.
Iterable<QueryDefinition> generateDefinitions(
DocumentNode schema,
String path,
DocumentNode document,
GeneratorOptions options,
SchemaMap schemaMap,
List<FragmentDefinitionNode> fragmentsCommon,
CanonicalVisitor canonicalVisitor,
) {
final fragments = <FragmentDefinitionNode>[];
final documentFragments =
document.definitions.whereType<FragmentDefinitionNode>();
if (documentFragments.isNotEmpty && fragmentsCommon.isNotEmpty) {
throw FragmentIgnoreException();
}
final operations =
document.definitions.whereType<OperationDefinitionNode>().toList();
return operations.map((operation) {
if (fragmentsCommon.isEmpty) {
fragments.addAll(documentFragments);
} else {
final fragmentsOperation =
_extractFragments(operation.selectionSet, fragmentsCommon);
document.definitions.addAll(fragmentsOperation);
fragments.addAll(fragmentsOperation);
}
final basename = p.basenameWithoutExtension(path).split('.').first;
final operationName = operation.name?.value ?? basename;
final schemaVisitor = SchemaDefinitionVisitor();
final objectVisitor = ObjectTypeDefinitionVisitor();
schema.accept(schemaVisitor);
schema.accept(objectVisitor);
String suffix;
switch (operation.type) {
case OperationType.subscription:
suffix = 'Subscription';
break;
case OperationType.mutation:
suffix = 'Mutation';
break;
case OperationType.query:
default:
suffix = 'Query';
break;
}
final rootTypeName =
(schemaVisitor.schemaDefinitionNode?.operationTypes ?? [])
.firstWhere((e) => e.operation == operation.type,
orElse: () => null)
?.type
?.name
?.value ??
suffix;
if (rootTypeName == null) {
throw Exception(
'''No root type was found for ${operation.type} $operationName.''');
}
final TypeDefinitionNode parentType = objectVisitor.getByName(rootTypeName);
final name = QueryName.fromPath(
path: createPathName([
ClassName(name: operationName),
ClassName(name: parentType.name.value)
], schemaMap.namingScheme));
final context = Context(
schema: schema,
options: options,
schemaMap: schemaMap,
path: [
TypeName(name: operationName),
TypeName(name: parentType.name.value)
],
currentType: parentType,
currentFieldName: null,
currentClassName: null,
generatedClasses: [],
inputsClasses: [],
fragments: fragments,
usedEnums: {},
usedInputObjects: {},
);
final visitor = GeneratorVisitor(
context: context,
);
final filteredDefinition = DocumentNode(
definitions: document.definitions
// filtering unused operations
.where((e) {
return e is! OperationDefinitionNode || e == operation;
}).toList(),
);
filteredDefinition.accept(visitor);
return QueryDefinition(
name: name,
operationName: operationName,
document: filteredDefinition,
classes: [
...canonicalVisitor.enums
.where((e) => context.usedEnums.contains(e.name)),
...visitor.context.generatedClasses,
...canonicalVisitor.inputObjects
.where((i) => context.usedInputObjects.contains(i.name)),
],
inputs: visitor.context.inputsClasses,
generateHelpers: options.generateHelpers,
suffix: suffix,
);
});
}
List<String> _extractCustomImports(
DocumentNode schema,
GeneratorOptions options,
) {
final typeVisitor = TypeDefinitionNodeVisitor();
schema.accept(typeVisitor);
return typeVisitor.types
.whereType<ScalarTypeDefinitionNode>()
.map((type) => gql.importsOfScalar(options, type.name.value))
.expand((i) => i)
.toSet()
.toList();
}
/// Creates class property object
ClassProperty createClassProperty({
@required ClassPropertyName fieldName,
ClassPropertyName fieldAlias,
@required Context context,
_OnNewClassFoundCallback onNewClassFound,
bool markAsUsed = true,
}) {
if (fieldName.name == context.schemaMap.typeNameField) {
return ClassProperty(
type: TypeName(name: 'String'),
name: fieldName,
annotations: ['JsonKey(name: \'${context.schemaMap.typeNameField}\')'],
isResolveType: true,
);
}
var finalFields = <Node>[];
if (context.currentType is ObjectTypeDefinitionNode) {
finalFields = (context.currentType as ObjectTypeDefinitionNode).fields;
} else if (context.currentType is InterfaceTypeDefinitionNode) {
finalFields = (context.currentType as InterfaceTypeDefinitionNode).fields;
} else if (context.currentType is InputObjectTypeDefinitionNode) {
finalFields = (context.currentType as InputObjectTypeDefinitionNode).fields;
}
final regularField = finalFields
.whereType<FieldDefinitionNode>()
.firstWhere((f) => f.name.value == fieldName.name, orElse: () => null);
final regularInputField = finalFields
.whereType<InputValueDefinitionNode>()
.firstWhere((f) => f.name.value == fieldName.name, orElse: () => null);
final fieldType = regularField?.type ?? regularInputField?.type;
if (fieldType == null) {
throw Exception(
'''Field $fieldName was not found in GraphQL type ${context.currentType?.name?.value}.
Make sure your query is correct and your schema is updated.''');
}
final nextType =
gql.getTypeByName(context.schema, fieldType, context: 'field node');
final aliasedContext = context.withAlias(
nextFieldName: fieldName,
nextClassName: ClassName(name: nextType.name.value),
alias: fieldAlias,
);
final nextClassName = aliasedContext.fullPathName();
final dartTypeName = gql.buildTypeName(fieldType, context.options,
dartType: true,
replaceLeafWith: ClassName.fromPath(path: nextClassName),
schema: context.schema);
logFn(context, aliasedContext.align + 1,
'${aliasedContext.path}[${aliasedContext.currentType.name.value}][${aliasedContext.currentClassName} ${aliasedContext.currentFieldName}] ${fieldAlias == null ? '' : '(${fieldAlias}) '}-> ${dartTypeName.namePrintable}');
if ((nextType is ObjectTypeDefinitionNode ||
nextType is UnionTypeDefinitionNode ||
nextType is InterfaceTypeDefinitionNode) &&
onNewClassFound != null) {
onNewClassFound(
aliasedContext.next(
nextType: nextType,
nextFieldName: ClassPropertyName(
name: regularField?.name?.value ?? regularInputField?.name?.value),
nextClassName: ClassName(name: nextType.name.value),
alias: fieldAlias,
),
);
}
final name = fieldAlias ?? fieldName;
// On custom scalars
final jsonKeyAnnotation = <String, String>{};
if (name.namePrintable != name.name) {
jsonKeyAnnotation['name'] = '\'${name.name}\'';
}
if (nextType is ScalarTypeDefinitionNode) {
final scalar = gql.getSingleScalarMap(context.options, nextType.name.value);
if (scalar.customParserImport != null &&
nextType.name.value == scalar.graphQLType) {
final graphqlTypeSafeStr = TypeName(
name: gql
.buildTypeName(fieldType, context.options,
dartType: false, schema: context.schema)
.dartTypeSafe);
final dartTypeSafeStr = TypeName(name: dartTypeName.dartTypeSafe);
jsonKeyAnnotation['fromJson'] =
'fromGraphQL${graphqlTypeSafeStr.namePrintable}ToDart${dartTypeSafeStr.namePrintable}';
jsonKeyAnnotation['toJson'] =
'fromDart${dartTypeSafeStr.namePrintable}ToGraphQL${graphqlTypeSafeStr.namePrintable}';
}
} // On enums
else if (nextType is EnumTypeDefinitionNode) {
if (markAsUsed) {
context.usedEnums.add(EnumName(name: nextType.name.value));
}
if (fieldType is ListTypeNode) {
final innerDartTypeName = gql.buildTypeName(
fieldType.type, context.options,
dartType: true,
replaceLeafWith: ClassName.fromPath(path: nextClassName),
schema: context.schema);
jsonKeyAnnotation['unknownEnumValue'] =
'${innerDartTypeName.namePrintable}.${ARTEMIS_UNKNOWN.name.namePrintable}';
} else {
jsonKeyAnnotation['unknownEnumValue'] =
'${dartTypeName.namePrintable}.${ARTEMIS_UNKNOWN.name.namePrintable}';
}
}
final fieldDirectives =
regularField?.directives ?? regularInputField?.directives;
var annotations = <String>[];
if (jsonKeyAnnotation.isNotEmpty) {
final jsonKey = jsonKeyAnnotation.entries
.map<String>((e) => '${e.key}: ${e.value}')
.join(', ');
annotations.add('JsonKey(${jsonKey})');
}
annotations.addAll(proceedDeprecated(fieldDirectives));
return ClassProperty(
type: dartTypeName,
name: name,
annotations: annotations,
isNonNull: fieldType.isNonNull,
);
}