1 | 'use strict';
|
2 |
|
3 | Object.defineProperty(exports, '__esModule', { value: true });
|
4 |
|
5 | const graphql = require('graphql');
|
6 | const visitorPluginCommon = require('@graphql-codegen/visitor-plugin-common');
|
7 | const javaCommon = require('@graphql-codegen/java-common');
|
8 | const pluginHelpers = require('@graphql-codegen/plugin-helpers');
|
9 | const crypto = require('crypto');
|
10 | const pluralize = require('pluralize');
|
11 | const camelCase = require('camel-case');
|
12 | const pascalCase = require('pascal-case');
|
13 | const path = require('path');
|
14 |
|
15 | const Imports = {
|
16 |
|
17 | String: 'java.lang.String',
|
18 | Boolean: 'java.lang.Boolean',
|
19 | Integer: 'java.lang.Integer',
|
20 | Object: 'java.lang.Object',
|
21 | Float: 'java.lang.Float',
|
22 | Long: 'java.lang.Long',
|
23 |
|
24 | Class: 'java.lang.Class',
|
25 | Arrays: 'java.util.Arrays',
|
26 | List: 'java.util.List',
|
27 | IOException: 'java.io.IOException',
|
28 | Collections: 'java.util.Collections',
|
29 | LinkedHashMap: 'java.util.LinkedHashMap',
|
30 | Map: 'java.util.Map',
|
31 |
|
32 | Nonnull: 'javax.annotation.Nonnull',
|
33 | Nullable: 'javax.annotation.Nullable',
|
34 | Override: 'java.lang.Override',
|
35 | Generated: 'javax.annotation.Generated',
|
36 |
|
37 | ScalarType: 'com.apollographql.apollo.api.ScalarType',
|
38 | GraphqlFragment: 'com.apollographql.apollo.api.GraphqlFragment',
|
39 | Operation: 'com.apollographql.apollo.api.Operation',
|
40 | OperationName: 'com.apollographql.apollo.api.OperationName',
|
41 | Mutation: 'com.apollographql.apollo.api.Mutation',
|
42 | Query: 'com.apollographql.apollo.api.Query',
|
43 | Subscription: 'com.apollographql.apollo.api.Subscription',
|
44 | ResponseField: 'com.apollographql.apollo.api.ResponseField',
|
45 | ResponseFieldMapper: 'com.apollographql.apollo.api.ResponseFieldMapper',
|
46 | ResponseFieldMarshaller: 'com.apollographql.apollo.api.ResponseFieldMarshaller',
|
47 | ResponseReader: 'com.apollographql.apollo.api.ResponseReader',
|
48 | ResponseWriter: 'com.apollographql.apollo.api.ResponseWriter',
|
49 | FragmentResponseFieldMapper: 'com.apollographql.apollo.api.FragmentResponseFieldMapper',
|
50 | UnmodifiableMapBuilder: 'com.apollographql.apollo.api.internal.UnmodifiableMapBuilder',
|
51 | Utils: 'com.apollographql.apollo.api.internal.Utils',
|
52 | InputType: 'com.apollographql.apollo.api.InputType',
|
53 | Input: 'com.apollographql.apollo.api.Input',
|
54 | InputFieldMarshaller: 'com.apollographql.apollo.api.InputFieldMarshaller',
|
55 | InputFieldWriter: 'com.apollographql.apollo.api.InputFieldWriter',
|
56 | };
|
57 |
|
58 | const SCALAR_TO_WRITER_METHOD = {
|
59 | ID: 'writeString',
|
60 | String: 'writeString',
|
61 | Int: 'writeInt',
|
62 | Boolean: 'writeBoolean',
|
63 | Float: 'writeDouble',
|
64 | };
|
65 | function isTypeNode(type) {
|
66 | return type && !!type.kind;
|
67 | }
|
68 | class BaseJavaVisitor extends visitorPluginCommon.BaseVisitor {
|
69 | constructor(_schema, rawConfig, additionalConfig) {
|
70 | super(rawConfig, {
|
71 | ...additionalConfig,
|
72 | scalars: visitorPluginCommon.buildScalars(_schema, { ID: 'String' }, javaCommon.JAVA_SCALARS),
|
73 | });
|
74 | this._schema = _schema;
|
75 | this._imports = new Set();
|
76 | }
|
77 | getPackage() {
|
78 | return '';
|
79 | }
|
80 | additionalContent() {
|
81 | return '';
|
82 | }
|
83 | getImports() {
|
84 | return Array.from(this._imports).map(imp => `import ${imp};`);
|
85 | }
|
86 | getImplementingTypes(node) {
|
87 | const allTypesMap = this._schema.getTypeMap();
|
88 | const implementingTypes = [];
|
89 | for (const graphqlType of Object.values(allTypesMap)) {
|
90 | if (graphqlType instanceof graphql.GraphQLObjectType) {
|
91 | const allInterfaces = graphqlType.getInterfaces();
|
92 | if (allInterfaces.find(int => int.name === node.name)) {
|
93 | implementingTypes.push(graphqlType.name);
|
94 | }
|
95 | }
|
96 | }
|
97 | return implementingTypes;
|
98 | }
|
99 | transformType(type) {
|
100 | let schemaType;
|
101 | let isNonNull;
|
102 | if (isTypeNode(type)) {
|
103 | const baseTypeNode = visitorPluginCommon.getBaseTypeNode(type);
|
104 | schemaType = this._schema.getType(baseTypeNode.name.value);
|
105 | isNonNull = type.kind === graphql.Kind.NON_NULL_TYPE;
|
106 | }
|
107 | else {
|
108 | schemaType = this._schema.getType(pluginHelpers.getBaseType(type).name);
|
109 | isNonNull = graphql.isNonNullType(type);
|
110 | }
|
111 | const javaType = this.getJavaClass(schemaType);
|
112 | const annotation = isNonNull ? 'Nonnull' : 'Nullable';
|
113 | const typeToUse = isTypeNode(type)
|
114 | ? this.getListTypeNodeWrapped(javaType, type)
|
115 | : this.getListTypeWrapped(javaType, type);
|
116 | return {
|
117 | baseType: schemaType.name,
|
118 | javaType,
|
119 | isNonNull,
|
120 | annotation,
|
121 | typeToUse,
|
122 | };
|
123 | }
|
124 |
|
125 | getJavaClass(schemaType) {
|
126 | let typeToUse = schemaType.name;
|
127 | if (graphql.isScalarType(schemaType)) {
|
128 | const scalar = this.scalars[schemaType.name] || 'Object';
|
129 | if (Imports[scalar]) {
|
130 | this._imports.add(Imports[scalar]);
|
131 | }
|
132 | typeToUse = scalar;
|
133 | }
|
134 | else if (graphql.isInputObjectType(schemaType)) {
|
135 |
|
136 | this._imports.add(`${this.config.typePackage}.${schemaType.name}`);
|
137 | }
|
138 | return typeToUse;
|
139 | }
|
140 | getListTypeWrapped(toWrap, type) {
|
141 | if (graphql.isNonNullType(type)) {
|
142 | return this.getListTypeWrapped(toWrap, type.ofType);
|
143 | }
|
144 | if (graphql.isListType(type)) {
|
145 | const child = this.getListTypeWrapped(toWrap, type.ofType);
|
146 | this._imports.add(Imports.List);
|
147 | return `List<${child}>`;
|
148 | }
|
149 | return toWrap;
|
150 | }
|
151 | getListTypeNodeWrapped(toWrap, type) {
|
152 | if (type.kind === graphql.Kind.NON_NULL_TYPE) {
|
153 | return this.getListTypeNodeWrapped(toWrap, type.type);
|
154 | }
|
155 | if (type.kind === graphql.Kind.LIST_TYPE) {
|
156 | const child = this.getListTypeNodeWrapped(toWrap, type.type);
|
157 | this._imports.add(Imports.List);
|
158 | return `List<${child}>`;
|
159 | }
|
160 | return toWrap;
|
161 | }
|
162 | }
|
163 |
|
164 | class InputTypeVisitor extends BaseJavaVisitor {
|
165 | constructor(_schema, rawConfig) {
|
166 | super(_schema, rawConfig, {
|
167 | typePackage: rawConfig.typePackage || 'type',
|
168 | });
|
169 | }
|
170 | getPackage() {
|
171 | return this.config.typePackage;
|
172 | }
|
173 | addInputMembers(cls, fields) {
|
174 | fields.forEach(field => {
|
175 | const type = this.transformType(field.type);
|
176 | const actualType = type.isNonNull ? type.typeToUse : `Input<${type.typeToUse}>`;
|
177 | const annotations = type.isNonNull ? [type.annotation] : [];
|
178 | this._imports.add(Imports[type.annotation]);
|
179 | cls.addClassMember(field.name.value, actualType, null, annotations, 'private', { final: true });
|
180 | cls.addClassMethod(field.name.value, actualType, `return this.${field.name.value};`, [], [type.annotation], 'public');
|
181 | });
|
182 | }
|
183 | addInputCtor(cls, className, fields) {
|
184 | const impl = fields.map(field => `this.${field.name.value} = ${field.name.value};`).join('\n');
|
185 | cls.addClassMethod(className, null, impl, fields.map(f => {
|
186 | const type = this.transformType(f.type);
|
187 | const actualType = type.isNonNull ? type.typeToUse : `Input<${type.typeToUse}>`;
|
188 | this._imports.add(Imports[type.annotation]);
|
189 | return {
|
190 | name: f.name.value,
|
191 | type: actualType,
|
192 | annotations: type.isNonNull ? [type.annotation] : [],
|
193 | };
|
194 | }), [], 'public');
|
195 | }
|
196 | getFieldWriterCall(field, listItemCall = false) {
|
197 | const baseType = visitorPluginCommon.getBaseTypeNode(field.type);
|
198 | const schemaType = this._schema.getType(baseType.name.value);
|
199 | const isNonNull = field.type.kind === graphql.Kind.NON_NULL_TYPE;
|
200 | let writerMethod = null;
|
201 | if (graphql.isScalarType(schemaType)) {
|
202 | writerMethod = SCALAR_TO_WRITER_METHOD[schemaType.name] || 'writeCustom';
|
203 | }
|
204 | else if (graphql.isInputObjectType(schemaType)) {
|
205 | return listItemCall
|
206 | ? `writeObject($item.marshaller())`
|
207 | : `writeObject("${field.name.value}", ${field.name.value}.value != null ? ${field.name.value}.value.marshaller() : null)`;
|
208 | }
|
209 | else if (graphql.isEnumType(schemaType)) {
|
210 | writerMethod = 'writeString';
|
211 | }
|
212 | return listItemCall
|
213 | ? `${writerMethod}($item)`
|
214 | : `${writerMethod}("${field.name.value}", ${field.name.value}${isNonNull ? '' : '.value'})`;
|
215 | }
|
216 | getFieldWithTypePrefix(field, wrapWith = null, applyNullable = false) {
|
217 | this._imports.add(Imports.Input);
|
218 | const typeToUse = this.getJavaClass(this._schema.getType(visitorPluginCommon.getBaseTypeNode(field.type).name.value));
|
219 | const isNonNull = field.type.kind === graphql.Kind.NON_NULL_TYPE;
|
220 | const name = field.kind === graphql.Kind.INPUT_VALUE_DEFINITION ? field.name.value : field.variable.name.value;
|
221 | if (isNonNull) {
|
222 | this._imports.add(Imports.Nonnull);
|
223 | return `@Nonnull ${typeToUse} ${name}`;
|
224 | }
|
225 | else {
|
226 | if (wrapWith) {
|
227 | return typeof wrapWith === 'function' ? `${wrapWith(typeToUse)} ${name}` : `${wrapWith}<${typeToUse}> ${name}`;
|
228 | }
|
229 | else {
|
230 | if (applyNullable) {
|
231 | this._imports.add(Imports.Nullable);
|
232 | }
|
233 | return `${applyNullable ? '@Nullable ' : ''}${typeToUse} ${name}`;
|
234 | }
|
235 | }
|
236 | }
|
237 | buildFieldsMarshaller(field) {
|
238 | const isNonNull = field.type.kind === graphql.Kind.NON_NULL_TYPE;
|
239 | const isArray = field.type.kind === graphql.Kind.LIST_TYPE ||
|
240 | (field.type.kind === graphql.Kind.NON_NULL_TYPE && field.type.type.kind === graphql.Kind.LIST_TYPE);
|
241 | const call = this.getFieldWriterCall(field, isArray);
|
242 | const baseTypeNode = visitorPluginCommon.getBaseTypeNode(field.type);
|
243 | const listItemType = this.getJavaClass(this._schema.getType(baseTypeNode.name.value));
|
244 | let result = '';
|
245 |
|
246 | if (isArray) {
|
247 | result = `writer.writeList("${field.name.value}", ${field.name.value}.value != null ? new InputFieldWriter.ListWriter() {
|
248 | @Override
|
249 | public void write(InputFieldWriter.ListItemWriter listItemWriter) throws IOException {
|
250 | for (${listItemType} $item : ${field.name.value}.value) {
|
251 | listItemWriter.${call};
|
252 | }
|
253 | }
|
254 | } : null);`;
|
255 | }
|
256 | else {
|
257 | result = visitorPluginCommon.indent(`writer.${call};`);
|
258 | }
|
259 | if (isNonNull) {
|
260 | return result;
|
261 | }
|
262 | else {
|
263 | return visitorPluginCommon.indentMultiline(`if(${field.name.value}.defined) {
|
264 | ${visitorPluginCommon.indentMultiline(result)}
|
265 | }`);
|
266 | }
|
267 | }
|
268 | buildMarshallerOverride(fields) {
|
269 | this._imports.add(Imports.Override);
|
270 | this._imports.add(Imports.IOException);
|
271 | this._imports.add(Imports.InputFieldWriter);
|
272 | this._imports.add(Imports.InputFieldMarshaller);
|
273 | const allMarshallers = fields.map(field => visitorPluginCommon.indentMultiline(this.buildFieldsMarshaller(field), 2));
|
274 | return visitorPluginCommon.indentMultiline(`@Override
|
275 | public InputFieldMarshaller marshaller() {
|
276 | return new InputFieldMarshaller() {
|
277 | @Override
|
278 | public void marshal(InputFieldWriter writer) throws IOException {
|
279 | ${allMarshallers.join('\n')}
|
280 | }
|
281 | };
|
282 | }`);
|
283 | }
|
284 | buildBuilderNestedClass(className, fields) {
|
285 | const builderClassName = 'Builder';
|
286 | const privateFields = fields
|
287 | .map(field => {
|
288 | const isArray = field.type.kind === graphql.Kind.LIST_TYPE ||
|
289 | (field.type.kind === graphql.Kind.NON_NULL_TYPE && field.type.type.kind === graphql.Kind.LIST_TYPE);
|
290 | const fieldType = this.getFieldWithTypePrefix(field, v => (!isArray ? `Input<${v}>` : `Input<List<${v}>>`));
|
291 | const isNonNull = field.type.kind === graphql.Kind.NON_NULL_TYPE;
|
292 | return `private ${fieldType}${isNonNull ? '' : ' = Input.absent()'};`;
|
293 | })
|
294 | .map(s => visitorPluginCommon.indent(s));
|
295 | const setters = fields
|
296 | .map(field => {
|
297 | const isArray = field.type.kind === graphql.Kind.LIST_TYPE ||
|
298 | (field.type.kind === graphql.Kind.NON_NULL_TYPE && field.type.type.kind === graphql.Kind.LIST_TYPE);
|
299 | const fieldType = this.getFieldWithTypePrefix(field, isArray ? 'List' : null);
|
300 | const isNonNull = field.type.kind === graphql.Kind.NON_NULL_TYPE;
|
301 | return `\npublic ${builderClassName} ${field.name.value}(${isNonNull ? '' : '@Nullable '}${fieldType}) {
|
302 | this.${field.name.value} = ${isNonNull ? field.name.value : `Input.fromNullable(${field.name.value})`};
|
303 | return this;
|
304 | }`;
|
305 | })
|
306 | .map(s => visitorPluginCommon.indentMultiline(s));
|
307 | const nonNullFields = fields
|
308 | .filter(f => f.type.kind === graphql.Kind.NON_NULL_TYPE)
|
309 | .map(nnField => {
|
310 | this._imports.add(Imports.Utils);
|
311 | return visitorPluginCommon.indent(`Utils.checkNotNull(${nnField.name.value}, "${nnField.name.value} == null");`, 1);
|
312 | });
|
313 | const ctor = '\n' + visitorPluginCommon.indent(`${builderClassName}() {}`);
|
314 | const buildFn = visitorPluginCommon.indentMultiline(`public ${className} build() {
|
315 | ${nonNullFields.join('\n')}
|
316 | return new ${className}(${fields.map(f => f.name.value).join(', ')});
|
317 | }`);
|
318 | const body = [...privateFields, ctor, ...setters, '', buildFn].join('\n');
|
319 | return visitorPluginCommon.indentMultiline(new javaCommon.JavaDeclarationBlock()
|
320 | .withName(builderClassName)
|
321 | .access('public')
|
322 | .final()
|
323 | .static()
|
324 | .withBlock(body)
|
325 | .asKind('class').string);
|
326 | }
|
327 | InputObjectTypeDefinition(node) {
|
328 | const className = node.name.value;
|
329 | this._imports.add(Imports.InputType);
|
330 | this._imports.add(Imports.Generated);
|
331 | const cls = new javaCommon.JavaDeclarationBlock()
|
332 | .annotate([`Generated("Apollo GraphQL")`])
|
333 | .access('public')
|
334 | .final()
|
335 | .asKind('class')
|
336 | .withName(className)
|
337 | .implements(['InputType']);
|
338 | this.addInputMembers(cls, node.fields);
|
339 | this.addInputCtor(cls, className, node.fields);
|
340 | cls.addClassMethod('builder', 'Builder', 'return new Builder();', [], [], 'public', { static: true });
|
341 | const marshallerOverride = this.buildMarshallerOverride(node.fields);
|
342 | const builderClass = this.buildBuilderNestedClass(className, node.fields);
|
343 | const classBlock = [marshallerOverride, '', builderClass].join('\n');
|
344 | cls.withBlock(classBlock);
|
345 | return cls.string;
|
346 | }
|
347 | }
|
348 |
|
349 | function visitFieldArguments(selection, imports) {
|
350 | if (!selection.arguments || selection.arguments.length === 0) {
|
351 | return 'null';
|
352 | }
|
353 | imports.add(Imports.UnmodifiableMapBuilder);
|
354 | imports.add(Imports.String);
|
355 | imports.add(Imports.Object);
|
356 | return graphql.visit(selection, {
|
357 | leave: {
|
358 | Field: (node) => {
|
359 | return (`new UnmodifiableMapBuilder<String, Object>(${node.arguments.length})` + node.arguments.join('') + '.build()');
|
360 | },
|
361 | Argument: (node) => {
|
362 | return `.put("${node.name.value}", ${node.value})`;
|
363 | },
|
364 | ObjectValue: (node) => {
|
365 | return `new UnmodifiableMapBuilder<String, Object>(${node.fields.length})` + node.fields.join('') + '.build()';
|
366 | },
|
367 | ObjectField: (node) => {
|
368 | return `.put("${node.name.value}", ${node.value})`;
|
369 | },
|
370 | Variable: (node) => {
|
371 | return `new UnmodifiableMapBuilder<String, Object>(2).put("kind", "Variable").put("variableName", "${node.name.value}").build()`;
|
372 | },
|
373 | StringValue: (node) => `"${node.value}"`,
|
374 | IntValue: (node) => `"${node.value}"`,
|
375 | FloatValue: (node) => `"${node.value}"`,
|
376 | },
|
377 | });
|
378 | }
|
379 |
|
380 | class OperationVisitor extends BaseJavaVisitor {
|
381 | constructor(_schema, rawConfig, _availableFragments) {
|
382 | super(_schema, rawConfig, {
|
383 | package: rawConfig.package || javaCommon.buildPackageNameFromPath(process.cwd()),
|
384 | fragmentPackage: rawConfig.fragmentPackage || 'fragment',
|
385 | typePackage: rawConfig.typePackage || 'type',
|
386 | });
|
387 | this._availableFragments = _availableFragments;
|
388 | this.visitingFragment = false;
|
389 | }
|
390 | printDocument(node) {
|
391 | return graphql.print(node)
|
392 | .replace(/\r?\n|\r/g, ' ')
|
393 | .replace(/"/g, '\\"')
|
394 | .trim();
|
395 | }
|
396 | getPackage() {
|
397 | return this.visitingFragment ? this.config.fragmentPackage : this.config.package;
|
398 | }
|
399 | addCtor(className, node, cls) {
|
400 | const variables = node.variableDefinitions || [];
|
401 | const hasVariables = variables.length > 0;
|
402 | const nonNullVariables = variables
|
403 | .filter(v => v.type.kind === graphql.Kind.NON_NULL_TYPE)
|
404 | .map(v => {
|
405 | this._imports.add(Imports.Utils);
|
406 | return `Utils.checkNotNull(${v.variable.name.value}, "${v.variable.name.value} == null");`;
|
407 | });
|
408 | const impl = [
|
409 | ...nonNullVariables,
|
410 | `this.variables = ${!hasVariables
|
411 | ? 'Operation.EMPTY_VARIABLES'
|
412 | : `new ${className}.Variables(${variables.map(v => v.variable.name.value).join(', ')})`};`,
|
413 | ].join('\n');
|
414 | cls.addClassMethod(className, null, impl, node.variableDefinitions.map(varDec => {
|
415 | const outputType = visitorPluginCommon.getBaseTypeNode(varDec.type).name.value;
|
416 | const schemaType = this._schema.getType(outputType);
|
417 | const javaClass = this.getJavaClass(schemaType);
|
418 | const typeToUse = this.getListTypeNodeWrapped(javaClass, varDec.type);
|
419 | const isNonNull = varDec.type.kind === graphql.Kind.NON_NULL_TYPE;
|
420 | return {
|
421 | name: varDec.variable.name.value,
|
422 | type: typeToUse,
|
423 | annotations: [isNonNull ? 'Nonnull' : 'Nullable'],
|
424 | };
|
425 | }), null, 'public');
|
426 | }
|
427 | getRootType(operation) {
|
428 | if (operation === 'query') {
|
429 | return this._schema.getQueryType();
|
430 | }
|
431 | else if (operation === 'mutation') {
|
432 | return this._schema.getMutationType();
|
433 | }
|
434 | else if (operation === 'subscription') {
|
435 | return this._schema.getSubscriptionType();
|
436 | }
|
437 | else {
|
438 | return null;
|
439 | }
|
440 | }
|
441 | createUniqueClassName(inUse, name, count = 0) {
|
442 | const possibleNewName = count === 0 ? name : `${name}${count}`;
|
443 | while (inUse.includes(possibleNewName)) {
|
444 | return this.createUniqueClassName(inUse, name, count + 1);
|
445 | }
|
446 | return possibleNewName;
|
447 | }
|
448 | transformSelectionSet(options, isRoot = true) {
|
449 | if (!options.result) {
|
450 | options.result = {};
|
451 | }
|
452 | if (!graphql.isObjectType(options.schemaType) && !graphql.isInterfaceType(options.schemaType)) {
|
453 | return options.result;
|
454 | }
|
455 | const className = this.createUniqueClassName(Object.keys(options.result), options.className);
|
456 | const cls = new javaCommon.JavaDeclarationBlock()
|
457 | .access('public')
|
458 | .asKind('class')
|
459 | .withName(className)
|
460 | .implements(options.implements || []);
|
461 | if (!options.nonStaticClass) {
|
462 | cls.static();
|
463 | }
|
464 | options.result[className] = cls;
|
465 | const fields = options.schemaType.getFields();
|
466 | const childFields = [...(options.additionalFields || [])];
|
467 | const childInlineFragments = [];
|
468 | const childFragmentSpread = [...(options.additionalFragments || [])];
|
469 | const selections = [...(options.selectionSet || [])];
|
470 | const responseFieldArr = [];
|
471 | for (const selection of selections) {
|
472 | if (selection.kind === graphql.Kind.FIELD) {
|
473 | this._imports.add(Imports.ResponseField);
|
474 | const field = fields[selection.name.value];
|
475 | const isObject = selection.selectionSet && selection.selectionSet.selections && selection.selectionSet.selections.length > 0;
|
476 | const isNonNull = graphql.isNonNullType(field.type);
|
477 | const fieldAnnotation = isNonNull ? 'Nonnull' : 'Nullable';
|
478 | this._imports.add(Imports[fieldAnnotation]);
|
479 | const baseType = pluginHelpers.getBaseType(field.type);
|
480 | const isList = graphql.isListType(field.type) || (graphql.isNonNullType(field.type) && graphql.isListType(field.type.ofType));
|
481 | if (isObject) {
|
482 | let childClsName = this.convertName(field.name);
|
483 | if (isList && pluralize.isPlural(childClsName)) {
|
484 | childClsName = pluralize.singular(childClsName);
|
485 | }
|
486 | this.transformSelectionSet({
|
487 | className: childClsName,
|
488 | result: options.result,
|
489 | selectionSet: selection.selectionSet.selections,
|
490 | schemaType: baseType,
|
491 | }, false);
|
492 | childFields.push({
|
493 | rawType: field.type,
|
494 | isObject: true,
|
495 | isList,
|
496 | isFragment: false,
|
497 | type: baseType,
|
498 | isNonNull,
|
499 | annotation: fieldAnnotation,
|
500 | className: childClsName,
|
501 | fieldName: field.name,
|
502 | });
|
503 | }
|
504 | else {
|
505 | const javaClass = this.getJavaClass(baseType);
|
506 | childFields.push({
|
507 | rawType: field.type,
|
508 | isObject: false,
|
509 | isFragment: false,
|
510 | isList: isList,
|
511 | type: baseType,
|
512 | isNonNull,
|
513 | annotation: fieldAnnotation,
|
514 | className: javaClass,
|
515 | fieldName: field.name,
|
516 | });
|
517 | }
|
518 | this._imports.add(Imports.ResponseField);
|
519 | this._imports.add(Imports.Collections);
|
520 | const operationArgs = visitFieldArguments(selection, this._imports);
|
521 | const responseFieldMethod = this._resolveResponseFieldMethodForBaseType(field.type);
|
522 | responseFieldArr.push(`ResponseField.${responseFieldMethod.fn}("${selection.alias ? selection.alias.value : selection.name.value}", "${selection.name.value}", ${operationArgs}, ${!graphql.isNonNullType(field.type)},${responseFieldMethod.custom ? ` CustomType.${baseType.name},` : ''} Collections.<ResponseField.Condition>emptyList())`);
|
523 | }
|
524 | else if (selection.kind === graphql.Kind.INLINE_FRAGMENT) {
|
525 | if (graphql.isUnionType(options.schemaType) || graphql.isInterfaceType(options.schemaType)) {
|
526 | childInlineFragments.push({
|
527 | onType: selection.typeCondition.name.value,
|
528 | node: selection,
|
529 | });
|
530 | }
|
531 | else {
|
532 | selections.push(...selection.selectionSet.selections);
|
533 | }
|
534 | }
|
535 | else if (selection.kind === graphql.Kind.FRAGMENT_SPREAD) {
|
536 | const fragment = this._availableFragments.find(f => f.name === selection.name.value);
|
537 | if (fragment) {
|
538 | childFragmentSpread.push(fragment);
|
539 | this._imports.add(`${this.config.fragmentPackage}.${fragment.name}`);
|
540 | }
|
541 | else {
|
542 | throw new Error(`Fragment with name ${selection.name.value} was not loaded as document!`);
|
543 | }
|
544 | }
|
545 | }
|
546 | if (childInlineFragments.length > 0) {
|
547 | const childFieldsBase = [...childFields];
|
548 | childFields.push(...childInlineFragments.map(inlineFragment => {
|
549 | const cls = `As${inlineFragment.onType}`;
|
550 | const schemaType = this._schema.getType(inlineFragment.onType);
|
551 | this.transformSelectionSet({
|
552 | additionalFields: childFieldsBase,
|
553 | additionalFragments: childFragmentSpread,
|
554 | className: cls,
|
555 | result: options.result,
|
556 | selectionSet: inlineFragment.node.selectionSet.selections,
|
557 | schemaType,
|
558 | }, false);
|
559 | this._imports.add(Imports.Nullable);
|
560 | return {
|
561 | isFragment: false,
|
562 | rawType: schemaType,
|
563 | isObject: true,
|
564 | isList: false,
|
565 | type: schemaType,
|
566 | isNonNull: false,
|
567 | annotation: 'Nullable',
|
568 | className: cls,
|
569 | fieldName: `as${inlineFragment.onType}`,
|
570 | };
|
571 | }));
|
572 | responseFieldArr.push(...childInlineFragments.map(f => {
|
573 | this._imports.add(Imports.Arrays);
|
574 | return `ResponseField.forInlineFragment("__typename", "__typename", Arrays.asList("${f.onType}"))`;
|
575 | }));
|
576 | }
|
577 | if (childFragmentSpread.length > 0) {
|
578 | responseFieldArr.push(`ResponseField.forFragment("__typename", "__typename", Arrays.asList(${childFragmentSpread
|
579 | .map(f => `"${f.onType}"`)
|
580 | .join(', ')}))`);
|
581 | this._imports.add(Imports.ResponseField);
|
582 | this._imports.add(Imports.Nonnull);
|
583 | this._imports.add(Imports.Arrays);
|
584 | const fragmentsClassName = 'Fragments';
|
585 | childFields.push({
|
586 | isObject: true,
|
587 | isList: false,
|
588 | isFragment: true,
|
589 | rawType: options.schemaType,
|
590 | type: options.schemaType,
|
591 | isNonNull: true,
|
592 | annotation: 'Nonnull',
|
593 | className: fragmentsClassName,
|
594 | fieldName: 'fragments',
|
595 | });
|
596 | const fragmentsClass = new javaCommon.JavaDeclarationBlock()
|
597 | .withName(fragmentsClassName)
|
598 | .access('public')
|
599 | .static()
|
600 | .final()
|
601 | .asKind('class');
|
602 | const fragmentMapperClass = new javaCommon.JavaDeclarationBlock()
|
603 | .withName('Mapper')
|
604 | .access('public')
|
605 | .static()
|
606 | .final()
|
607 | .implements([`FragmentResponseFieldMapper<${fragmentsClassName}>`])
|
608 | .asKind('class');
|
609 | fragmentsClass.addClassMethod(fragmentsClassName, null, childFragmentSpread
|
610 | .map(spread => {
|
611 | const varName = camelCase.camelCase(spread.name);
|
612 | this._imports.add(Imports.Utils);
|
613 | return `this.${varName} = Utils.checkNotNull(${varName}, "${varName} == null");`;
|
614 | })
|
615 | .join('\n'), childFragmentSpread.map(spread => ({
|
616 | name: camelCase.camelCase(spread.name),
|
617 | type: spread.name,
|
618 | annotations: ['Nonnull'],
|
619 | })), [], 'public');
|
620 | for (const spread of childFragmentSpread) {
|
621 | const fragmentVarName = camelCase.camelCase(spread.name);
|
622 | fragmentsClass.addClassMember(fragmentVarName, spread.name, null, ['Nonnull'], 'private', { final: true });
|
623 | fragmentsClass.addClassMethod(fragmentVarName, spread.name, `return this.${fragmentVarName};`, [], ['Nonnull'], 'public', {}, []);
|
624 | fragmentMapperClass.addClassMember(`${fragmentVarName}FieldMapper`, `${spread.name}.Mapper`, `new ${spread.name}.Mapper()`, [], 'private', { final: true });
|
625 | }
|
626 | fragmentMapperClass.addClassMethod('map', fragmentsClassName, `
|
627 | ${childFragmentSpread
|
628 | .map(spread => {
|
629 | const fragmentVarName = camelCase.camelCase(spread.name);
|
630 | return `${spread.name} ${fragmentVarName} = null;
|
631 | if (${spread.name}.POSSIBLE_TYPES.contains(conditionalType)) {
|
632 | ${fragmentVarName} = ${fragmentVarName}FieldMapper.map(reader);
|
633 | }`;
|
634 | })
|
635 | .join('\n')}
|
636 |
|
637 | return new Fragments(${childFragmentSpread
|
638 | .map(spread => {
|
639 | const fragmentVarName = camelCase.camelCase(spread.name);
|
640 | return `Utils.checkNotNull(${fragmentVarName}, "${fragmentVarName} == null")`;
|
641 | })
|
642 | .join(', ')});
|
643 | `, [
|
644 | {
|
645 | name: 'reader',
|
646 | type: 'ResponseReader',
|
647 | },
|
648 | {
|
649 | name: 'conditionalType',
|
650 | type: 'String',
|
651 | annotations: ['Nonnull'],
|
652 | },
|
653 | ], ['Nonnull'], 'public', {}, ['Override']);
|
654 | this._imports.add(Imports.String);
|
655 | this._imports.add(Imports.ResponseReader);
|
656 | this._imports.add(Imports.ResponseFieldMarshaller);
|
657 | this._imports.add(Imports.ResponseWriter);
|
658 | fragmentsClass.addClassMethod('marshaller', 'ResponseFieldMarshaller', `return new ResponseFieldMarshaller() {
|
659 | @Override
|
660 | public void marshal(ResponseWriter writer) {
|
661 | ${childFragmentSpread
|
662 | .map(spread => {
|
663 | const fragmentVarName = camelCase.camelCase(spread.name);
|
664 | return visitorPluginCommon.indentMultiline(`final ${spread.name} $${fragmentVarName} = ${fragmentVarName};\nif ($${fragmentVarName} != null) { $${fragmentVarName}.marshaller().marshal(writer); }`, 2);
|
665 | })
|
666 | .join('\n')}
|
667 | }
|
668 | };
|
669 | `, [], [], 'public');
|
670 | fragmentsClass.addClassMember('$toString', 'String', null, [], 'private', { volatile: true });
|
671 | fragmentsClass.addClassMember('$hashCode', 'int', null, [], 'private', { volatile: true });
|
672 | fragmentsClass.addClassMember('$hashCodeMemoized', 'boolean', null, [], 'private', { volatile: true });
|
673 | fragmentsClass.addClassMethod('toString', 'String', `if ($toString == null) {
|
674 | $toString = "${fragmentsClassName}{"
|
675 | ${childFragmentSpread
|
676 | .map(spread => {
|
677 | const varName = camelCase.camelCase(spread.name);
|
678 | return visitorPluginCommon.indent(`+ "${varName}=" + ${varName} + ", "`, 2);
|
679 | })
|
680 | .join('\n')}
|
681 | + "}";
|
682 | }
|
683 |
|
684 | return $toString;`, [], [], 'public', {}, ['Override']);
|
685 |
|
686 | fragmentsClass.addClassMethod('equals', 'boolean', `if (o == this) {
|
687 | return true;
|
688 | }
|
689 | if (o instanceof ${fragmentsClassName}) {
|
690 | ${fragmentsClassName} that = (${fragmentsClassName}) o;
|
691 | return ${childFragmentSpread
|
692 | .map(spread => {
|
693 | const varName = camelCase.camelCase(spread.name);
|
694 | return `this.${varName}.equals(that.${varName})`;
|
695 | })
|
696 | .join(' && ')};
|
697 | }
|
698 |
|
699 | return false;`, [{ name: 'o', type: 'Object' }], [], 'public', {}, ['Override']);
|
700 |
|
701 | fragmentsClass.addClassMethod('hashCode', 'int', `if (!$hashCodeMemoized) {
|
702 | int h = 1;
|
703 | ${childFragmentSpread
|
704 | .map(spread => {
|
705 | const varName = camelCase.camelCase(spread.name);
|
706 | return visitorPluginCommon.indentMultiline(`h *= 1000003;\nh ^= ${varName}.hashCode();`, 1);
|
707 | })
|
708 | .join('\n')}
|
709 | $hashCode = h;
|
710 | $hashCodeMemoized = true;
|
711 | }
|
712 |
|
713 | return $hashCode;`, [], [], 'public', {}, ['Override']);
|
714 | this._imports.add(Imports.FragmentResponseFieldMapper);
|
715 | fragmentsClass.nestedClass(fragmentMapperClass);
|
716 | cls.nestedClass(fragmentsClass);
|
717 | }
|
718 | if (responseFieldArr.length > 0 && !isRoot) {
|
719 | responseFieldArr.unshift(`ResponseField.forString("__typename", "__typename", null, false, Collections.<ResponseField.Condition>emptyList())`);
|
720 | }
|
721 | if (!isRoot) {
|
722 | this._imports.add(Imports.Nonnull);
|
723 | childFields.unshift({
|
724 | isObject: false,
|
725 | isFragment: false,
|
726 | isList: false,
|
727 | type: graphql.GraphQLString,
|
728 | rawType: graphql.GraphQLString,
|
729 | isNonNull: true,
|
730 | annotation: 'Nonnull',
|
731 | className: 'String',
|
732 | fieldName: '__typename',
|
733 | });
|
734 | }
|
735 |
|
736 | childFields.forEach(c => {
|
737 | cls.addClassMember(c.fieldName, this.getListTypeWrapped(c.className, c.rawType), null, [c.annotation], 'private', { final: true });
|
738 | });
|
739 |
|
740 | cls.addClassMember('$toString', 'String', null, [], 'private', { volatile: true });
|
741 | cls.addClassMember('$hashCode', 'int', null, [], 'private', { volatile: true });
|
742 | cls.addClassMember('$hashCodeMemoized', 'boolean', null, [], 'private', { volatile: true });
|
743 |
|
744 | cls.addClassMember('$responseFields', 'ResponseField[]', `{\n${visitorPluginCommon.indentMultiline(responseFieldArr.join(',\n'), 2) + '\n }'}`, [], null, { static: true, final: true });
|
745 |
|
746 | this._imports.add(Imports.Utils);
|
747 | cls.addClassMethod(className, null, childFields
|
748 | .map(c => `this.${c.fieldName} = ${c.isNonNull ? `Utils.checkNotNull(${c.fieldName}, "${c.fieldName} == null")` : c.fieldName};`)
|
749 | .join('\n'), childFields.map(c => ({
|
750 | name: c.fieldName,
|
751 | type: this.getListTypeWrapped(c.className, c.rawType),
|
752 | annotations: [c.annotation],
|
753 | })), null, 'public');
|
754 |
|
755 | childFields.forEach(c => {
|
756 | cls.addClassMethod(c.fieldName, this.getListTypeWrapped(c.className, c.rawType), `return this.${c.fieldName};`, [], [c.annotation], 'public', {});
|
757 | });
|
758 |
|
759 | cls.addClassMethod('toString', 'String', `if ($toString == null) {
|
760 | $toString = "${className}{"
|
761 | ${childFields.map(c => visitorPluginCommon.indent(`+ "${c.fieldName}=" + ${c.fieldName} + ", "`, 2)).join('\n')}
|
762 | + "}";
|
763 | }
|
764 |
|
765 | return $toString;`, [], [], 'public', {}, ['Override']);
|
766 |
|
767 | cls.addClassMethod('equals', 'boolean', `if (o == this) {
|
768 | return true;
|
769 | }
|
770 | if (o instanceof ${className}) {
|
771 | ${className} that = (${className}) o;
|
772 | return ${childFields
|
773 | .map(c => c.isNonNull
|
774 | ? `this.${c.fieldName}.equals(that.${c.fieldName})`
|
775 | : `((this.${c.fieldName} == null) ? (that.${c.fieldName} == null) : this.${c.fieldName}.equals(that.${c.fieldName}))`)
|
776 | .join(' && ')};
|
777 | }
|
778 |
|
779 | return false;`, [{ name: 'o', type: 'Object' }], [], 'public', {}, ['Override']);
|
780 |
|
781 | cls.addClassMethod('hashCode', 'int', `if (!$hashCodeMemoized) {
|
782 | int h = 1;
|
783 | ${childFields
|
784 | .map(f => visitorPluginCommon.indentMultiline(`h *= 1000003;\nh ^= ${!f.isNonNull ? `(${f.fieldName} == null) ? 0 : ` : ''}${f.fieldName}.hashCode();`, 1))
|
785 | .join('\n')}
|
786 | $hashCode = h;
|
787 | $hashCodeMemoized = true;
|
788 | }
|
789 |
|
790 | return $hashCode;`, [], [], 'public', {}, ['Override']);
|
791 | this._imports.add(Imports.ResponseReader);
|
792 | this._imports.add(Imports.ResponseFieldMarshaller);
|
793 | this._imports.add(Imports.ResponseWriter);
|
794 |
|
795 | cls.addClassMethod('marshaller', 'ResponseFieldMarshaller', `return new ResponseFieldMarshaller() {
|
796 | @Override
|
797 | public void marshal(ResponseWriter writer) {
|
798 | ${childFields
|
799 | .map((f, index) => {
|
800 | const writerMethod = this._getWriterMethodByType(f.type);
|
801 | if (f.isList) {
|
802 | return visitorPluginCommon.indentMultiline(`writer.writeList($responseFields[${index}], ${f.fieldName}, new ResponseWriter.ListWriter() {
|
803 | @Override
|
804 | public void write(Object value, ResponseWriter.ListItemWriter listItemWriter) {
|
805 | listItemWriter.${writerMethod.name}(((${f.className}) value)${writerMethod.useMarshaller ? '.marshaller()' : ''});
|
806 | }
|
807 | });`, 2);
|
808 | }
|
809 | let fValue = `${f.fieldName}${writerMethod.useMarshaller ? '.marshaller()' : ''}`;
|
810 | if (writerMethod.checkNull || !f.isNonNull) {
|
811 | fValue = `${f.fieldName} != null ? ${fValue} : null`;
|
812 | }
|
813 | return visitorPluginCommon.indent(`writer.${writerMethod.name}(${writerMethod.castTo ? `(${writerMethod.castTo}) ` : ''}$responseFields[${index}], ${fValue});`, 2);
|
814 | })
|
815 | .join('\n')}
|
816 | }
|
817 | };`, [], [], 'public');
|
818 | cls.nestedClass(this.buildMapperClass(className, childFields));
|
819 | return options.result;
|
820 | }
|
821 | getReaderFn(baseType) {
|
822 | if (graphql.isScalarType(baseType)) {
|
823 | if (baseType.name === 'String') {
|
824 | return { fn: `readString` };
|
825 | }
|
826 | else if (baseType.name === 'Int') {
|
827 | return { fn: `readInt` };
|
828 | }
|
829 | else if (baseType.name === 'Float') {
|
830 | return { fn: `readDouble` };
|
831 | }
|
832 | else if (baseType.name === 'Boolean') {
|
833 | return { fn: `readBoolean` };
|
834 | }
|
835 | else {
|
836 | return { fn: `readCustomType`, custom: true };
|
837 | }
|
838 | }
|
839 | else if (graphql.isEnumType(baseType)) {
|
840 | return { fn: `readString` };
|
841 | }
|
842 | else {
|
843 | return { fn: `readObject`, object: baseType.name };
|
844 | }
|
845 | }
|
846 | buildMapperClass(parentClassName, childFields) {
|
847 | const wrapList = (childField, rawType, edgeStr) => {
|
848 | if (graphql.isNonNullType(rawType)) {
|
849 | return wrapList(childField, rawType.ofType, edgeStr);
|
850 | }
|
851 | if (graphql.isListType(rawType)) {
|
852 | const typeStr = this.getListTypeWrapped(childField.className, rawType.ofType);
|
853 | const innerContent = wrapList(childField, rawType.ofType, edgeStr);
|
854 | const inner = graphql.isListType(rawType.ofType) ? `return listItemReader.readList(${innerContent});` : innerContent;
|
855 | return `new ResponseReader.ListReader<${typeStr}>() {
|
856 | @Override
|
857 | public ${typeStr} read(ResponseReader.ListItemReader listItemReader) {
|
858 | ${visitorPluginCommon.indentMultiline(inner, 2)}
|
859 | }
|
860 | }`;
|
861 | }
|
862 | return edgeStr;
|
863 | };
|
864 | this._imports.add(Imports.ResponseReader);
|
865 | const mapperBody = childFields.map((f, index) => {
|
866 | const varDec = `final ${this.getListTypeWrapped(f.className, f.rawType)} ${f.fieldName} =`;
|
867 | const readerFn = this.getReaderFn(f.type);
|
868 | if (f.isFragment) {
|
869 | return `${varDec} reader.readConditional($responseFields[${index}], new ResponseReader.ConditionalTypeReader<${f.className}>() {
|
870 | @Override
|
871 | public ${f.className} read(String conditionalType, ResponseReader reader) {
|
872 | return fragmentsFieldMapper.map(reader, conditionalType);
|
873 | }
|
874 | });`;
|
875 | }
|
876 | else if (f.isList) {
|
877 | const listReader = readerFn.object
|
878 | ? `return listItemReader.${readerFn.fn}(new ResponseReader.ObjectReader<Item>() {
|
879 | @Override
|
880 | public Item read(ResponseReader reader) {
|
881 | return ${f.fieldName}FieldMapper.map(reader);
|
882 | }
|
883 | });`
|
884 | : `return listItemReader.${readerFn.fn}();`;
|
885 | const wrappedList = wrapList(f, f.rawType, listReader);
|
886 | return `${varDec} reader.readList($responseFields[${index}], ${wrappedList});`;
|
887 | }
|
888 | else if (readerFn.object) {
|
889 | return `${varDec} reader.readObject($responseFields[${index}], new ResponseReader.ObjectReader<${f.className}>() {
|
890 | @Override
|
891 | public ${f.className} read(ResponseReader reader) {
|
892 | return ${f.fieldName}FieldMapper.map(reader);
|
893 | }
|
894 | });`;
|
895 | }
|
896 | else {
|
897 | return `${varDec} reader.${readerFn.fn}(${readerFn.custom ? '(ResponseField.CustomTypeField) ' : ''}$responseFields[${index}]);`;
|
898 | }
|
899 | });
|
900 | const mapperImpl = [
|
901 | ...mapperBody,
|
902 | `return new ${parentClassName}(${childFields.map(f => f.fieldName).join(', ')});`,
|
903 | ].join('\n');
|
904 | const cls = new javaCommon.JavaDeclarationBlock()
|
905 | .access('public')
|
906 | .static()
|
907 | .final()
|
908 | .asKind('class')
|
909 | .withName('Mapper')
|
910 | .implements([`ResponseFieldMapper<${parentClassName}>`])
|
911 | .addClassMethod('map', parentClassName, mapperImpl, [
|
912 | {
|
913 | name: 'reader',
|
914 | type: 'ResponseReader',
|
915 | },
|
916 | ], [], 'public', {}, ['Override']);
|
917 | childFields
|
918 | .filter(c => c.isObject)
|
919 | .forEach(childField => {
|
920 | cls.addClassMember(`${childField.fieldName}FieldMapper`, `${childField.className}.Mapper`, `new ${childField.className}.Mapper()`, [], 'private', { final: true });
|
921 | });
|
922 | return cls;
|
923 | }
|
924 | _resolveResponseFieldMethodForBaseType(baseType) {
|
925 | if (graphql.isListType(baseType)) {
|
926 | return { fn: `forList` };
|
927 | }
|
928 | else if (graphql.isNonNullType(baseType)) {
|
929 | return this._resolveResponseFieldMethodForBaseType(baseType.ofType);
|
930 | }
|
931 | else if (graphql.isScalarType(baseType)) {
|
932 | if (baseType.name === 'String') {
|
933 | return { fn: `forString` };
|
934 | }
|
935 | else if (baseType.name === 'Int') {
|
936 | return { fn: `forInt` };
|
937 | }
|
938 | else if (baseType.name === 'Float') {
|
939 | return { fn: `forDouble` };
|
940 | }
|
941 | else if (baseType.name === 'Boolean') {
|
942 | return { fn: `forBoolean` };
|
943 | }
|
944 | else {
|
945 | this._imports.add(`${this.config.typePackage}.CustomType`);
|
946 | return { fn: `forCustomType`, custom: true };
|
947 | }
|
948 | }
|
949 | else if (graphql.isEnumType(baseType)) {
|
950 | return { fn: `forEnum` };
|
951 | }
|
952 | else {
|
953 | return { fn: `forObject` };
|
954 | }
|
955 | }
|
956 | FragmentDefinition(node) {
|
957 | this.visitingFragment = true;
|
958 | const className = node.name.value;
|
959 | const schemaType = this._schema.getType(node.typeCondition.name.value);
|
960 | this._imports.add(Imports.Arrays);
|
961 | this._imports.add(Imports.GraphqlFragment);
|
962 | this._imports.add(Imports.List);
|
963 | this._imports.add(Imports.String);
|
964 | this._imports.add(Imports.Collections);
|
965 | this._imports.add(Imports.Override);
|
966 | this._imports.add(Imports.Generated);
|
967 | this._imports.add(Imports.ResponseFieldMapper);
|
968 | const dataClasses = this.transformSelectionSet({
|
969 | className: className,
|
970 | nonStaticClass: true,
|
971 | implements: ['GraphqlFragment'],
|
972 | selectionSet: node.selectionSet && node.selectionSet.selections ? node.selectionSet.selections : [],
|
973 | result: {},
|
974 | schemaType: schemaType,
|
975 | }, false);
|
976 | const rootCls = dataClasses[className];
|
977 | const printed = this.printDocument(node);
|
978 | rootCls.addClassMember('FRAGMENT_DEFINITION', 'String', `"${printed}"`, [], 'public', {
|
979 | static: true,
|
980 | final: true,
|
981 | });
|
982 | const possibleTypes = graphql.isObjectType(schemaType) ? [schemaType.name] : this.getImplementingTypes(schemaType);
|
983 | rootCls.addClassMember('POSSIBLE_TYPES', 'List<String>', `Collections.unmodifiableList(Arrays.asList(${possibleTypes.map(t => `"${t}"`).join(', ')}))`, [], 'public', { static: true, final: true });
|
984 | Object.keys(dataClasses)
|
985 | .filter(name => name !== className)
|
986 | .forEach(clsName => {
|
987 | rootCls.nestedClass(dataClasses[clsName]);
|
988 | });
|
989 | return rootCls.string;
|
990 | }
|
991 | OperationDefinition(node) {
|
992 | this.visitingFragment = false;
|
993 | const operationType = pascalCase.pascalCase(node.operation);
|
994 | const operationSchemaType = this.getRootType(node.operation);
|
995 | const className = node.name.value.endsWith(operationType) ? operationType : `${node.name.value}${operationType}`;
|
996 | this._imports.add(Imports[operationType]);
|
997 | this._imports.add(Imports.String);
|
998 | this._imports.add(Imports.Override);
|
999 | this._imports.add(Imports.Generated);
|
1000 | this._imports.add(Imports.OperationName);
|
1001 | this._imports.add(Imports.Operation);
|
1002 | this._imports.add(Imports.ResponseFieldMapper);
|
1003 | const cls = new javaCommon.JavaDeclarationBlock()
|
1004 | .annotate([`Generated("Apollo GraphQL")`])
|
1005 | .access('public')
|
1006 | .final()
|
1007 | .asKind('class')
|
1008 | .withName(className);
|
1009 | const printed = this.printDocument(node);
|
1010 | cls.implements([
|
1011 | `${operationType}<${className}.Data, ${className}.Data, ${node.variableDefinitions.length === 0 ? 'Operation' : className}.Variables>`,
|
1012 | ]);
|
1013 | cls.addClassMember('OPERATION_DEFINITION', 'String', `"${printed}"`, [], 'public', { static: true, final: true });
|
1014 | cls.addClassMember('QUERY_DOCUMENT', 'String', 'OPERATION_DEFINITION', [], 'public', { static: true, final: true });
|
1015 | cls.addClassMember('OPERATION_NAME', 'OperationName', `new OperationName() {
|
1016 | @Override
|
1017 | public String name() {
|
1018 | return "${node.name.value}";
|
1019 | }
|
1020 | }`, [], 'public', { static: true, final: true });
|
1021 | cls.addClassMember('variables', `${node.variableDefinitions.length === 0 ? 'Operation' : className}.Variables`, null, [], 'private', { final: true });
|
1022 | cls.addClassMethod('queryDocument', `String`, `return QUERY_DOCUMENT;`, [], [], 'public', {}, ['Override']);
|
1023 | cls.addClassMethod('wrapData', `${className}.Data`, `return data;`, [
|
1024 | {
|
1025 | name: 'data',
|
1026 | type: `${className}.Data`,
|
1027 | },
|
1028 | ], [], 'public', {}, ['Override']);
|
1029 | cls.addClassMethod('variables', `${node.variableDefinitions.length === 0 ? 'Operation' : className}.Variables`, `return variables;`, [], [], 'public', {}, ['Override']);
|
1030 | cls.addClassMethod('responseFieldMapper', `ResponseFieldMapper<${className}.Data>`, `return new Data.Mapper();`, [], [], 'public', {}, ['Override']);
|
1031 | cls.addClassMethod('builder', `Builder`, `return new Builder();`, [], [], 'public', { static: true }, []);
|
1032 | cls.addClassMethod('name', `OperationName`, `return OPERATION_NAME;`, [], [], 'public', {}, ['Override']);
|
1033 | cls.addClassMethod('operationId', `String`, `return "${crypto.createHash('md5').update(printed).digest('hex')}";`, [], [], 'public', {}, []);
|
1034 | this.addCtor(className, node, cls);
|
1035 | this._imports.add(Imports.Operation);
|
1036 | const dataClasses = this.transformSelectionSet({
|
1037 | className: 'Data',
|
1038 | implements: ['Operation.Data'],
|
1039 | selectionSet: node.selectionSet && node.selectionSet.selections ? node.selectionSet.selections : [],
|
1040 | result: {},
|
1041 | schemaType: operationSchemaType,
|
1042 | });
|
1043 | Object.keys(dataClasses).forEach(className => {
|
1044 | cls.nestedClass(dataClasses[className]);
|
1045 | });
|
1046 | cls.nestedClass(this.createBuilderClass(className, node.variableDefinitions || []));
|
1047 | cls.nestedClass(this.createVariablesClass(className, node.variableDefinitions || []));
|
1048 | return cls.string;
|
1049 | }
|
1050 | createVariablesClass(parentClassName, variables) {
|
1051 | const className = 'Variables';
|
1052 | const cls = new javaCommon.JavaDeclarationBlock()
|
1053 | .static()
|
1054 | .access('public')
|
1055 | .final()
|
1056 | .asKind('class')
|
1057 | .extends(['Operation.Variables'])
|
1058 | .withName(className);
|
1059 | const ctorImpl = [];
|
1060 | const ctorArgs = [];
|
1061 | variables.forEach(variable => {
|
1062 | ctorImpl.push(`this.${variable.variable.name.value} = ${variable.variable.name.value};`);
|
1063 | ctorImpl.push(`this.valueMap.put("${variable.variable.name.value}", ${variable.variable.name.value});`);
|
1064 | const baseTypeNode = visitorPluginCommon.getBaseTypeNode(variable.type);
|
1065 | const schemaType = this._schema.getType(baseTypeNode.name.value);
|
1066 | const javaClass = this.getJavaClass(schemaType);
|
1067 | const annotation = graphql.isNonNullType(variable.type) ? 'Nullable' : 'Nonnull';
|
1068 | this._imports.add(Imports[annotation]);
|
1069 | ctorArgs.push({ name: variable.variable.name.value, type: javaClass, annotations: [annotation] });
|
1070 | cls.addClassMember(variable.variable.name.value, javaClass, null, [annotation], 'private');
|
1071 | cls.addClassMethod(variable.variable.name.value, javaClass, `return ${variable.variable.name.value};`, [], [], 'public');
|
1072 | });
|
1073 | this._imports.add(Imports.LinkedHashMap);
|
1074 | this._imports.add(Imports.Map);
|
1075 | cls.addClassMethod(className, null, ctorImpl.join('\n'), ctorArgs, [], 'public');
|
1076 | cls.addClassMember('valueMap', 'Map<String, Object>', 'new LinkedHashMap<>()', [], 'private', {
|
1077 | final: true,
|
1078 | transient: true,
|
1079 | });
|
1080 | cls.addClassMethod('valueMap', 'Map<String, Object>', 'return Collections.unmodifiableMap(valueMap);', [], [], 'public', {}, ['Override']);
|
1081 | const marshallerImpl = `return new InputFieldMarshaller() {
|
1082 | @Override
|
1083 | public void marshal(InputFieldWriter writer) throws IOException {
|
1084 | ${variables
|
1085 | .map(v => {
|
1086 | const baseTypeNode = visitorPluginCommon.getBaseTypeNode(v.type);
|
1087 | const schemaType = this._schema.getType(baseTypeNode.name.value);
|
1088 | const writerMethod = this._getWriterMethodByType(schemaType, true);
|
1089 | return visitorPluginCommon.indent(`writer.${writerMethod.name}("${v.variable.name.value}", ${writerMethod.checkNull
|
1090 | ? `${v.variable.name.value} != null ? ${v.variable.name.value}${writerMethod.useMarshaller ? '.marshaller()' : ''} : null`
|
1091 | : v.variable.name.value});`, 2);
|
1092 | })
|
1093 | .join('\n')}
|
1094 | }
|
1095 | };`;
|
1096 | this._imports.add(Imports.InputFieldMarshaller);
|
1097 | this._imports.add(Imports.InputFieldWriter);
|
1098 | this._imports.add(Imports.IOException);
|
1099 | cls.addClassMethod('marshaller', 'InputFieldMarshaller', marshallerImpl, [], [], 'public', {}, ['Override']);
|
1100 | return cls;
|
1101 | }
|
1102 | _getWriterMethodByType(schemaType, idAsString = false) {
|
1103 | if (graphql.isScalarType(schemaType)) {
|
1104 | if (SCALAR_TO_WRITER_METHOD[schemaType.name] && (idAsString || schemaType.name !== 'ID')) {
|
1105 | return {
|
1106 | name: SCALAR_TO_WRITER_METHOD[schemaType.name],
|
1107 | checkNull: false,
|
1108 | useMarshaller: false,
|
1109 | };
|
1110 | }
|
1111 | return { name: 'writeCustom', checkNull: false, useMarshaller: false, castTo: 'ResponseField.CustomTypeField' };
|
1112 | }
|
1113 | else if (graphql.isInputObjectType(schemaType)) {
|
1114 | return { name: 'writeObject', checkNull: true, useMarshaller: true };
|
1115 | }
|
1116 | else if (graphql.isEnumType(schemaType)) {
|
1117 | return { name: 'writeString', checkNull: false, useMarshaller: false };
|
1118 | }
|
1119 | else if (graphql.isObjectType(schemaType) || graphql.isInterfaceType(schemaType)) {
|
1120 | return { name: 'writeObject', checkNull: true, useMarshaller: true };
|
1121 | }
|
1122 | return { name: 'writeString', useMarshaller: false, checkNull: false };
|
1123 | }
|
1124 | createBuilderClass(parentClassName, variables) {
|
1125 | const builderClassName = 'Builder';
|
1126 | const cls = new javaCommon.JavaDeclarationBlock()
|
1127 | .static()
|
1128 | .final()
|
1129 | .access('public')
|
1130 | .asKind('class')
|
1131 | .withName(builderClassName)
|
1132 | .addClassMethod(builderClassName, null, '');
|
1133 | variables.forEach(variable => {
|
1134 | const baseTypeNode = visitorPluginCommon.getBaseTypeNode(variable.type);
|
1135 | const schemaType = this._schema.getType(baseTypeNode.name.value);
|
1136 | const javaClass = this.getJavaClass(schemaType);
|
1137 | const annotation = graphql.isNonNullType(variable.type) ? 'Nonnull' : 'Nullable';
|
1138 | this._imports.add(Imports[annotation]);
|
1139 | cls.addClassMember(variable.variable.name.value, javaClass, null, [annotation], 'private');
|
1140 | cls.addClassMethod(variable.variable.name.value, builderClassName, `this.${variable.variable.name.value} = ${variable.variable.name.value};\nreturn this;`, [
|
1141 | {
|
1142 | name: variable.variable.name.value,
|
1143 | type: javaClass,
|
1144 | annotations: [annotation],
|
1145 | },
|
1146 | ], [], 'public');
|
1147 | });
|
1148 | this._imports.add(Imports.Utils);
|
1149 | const nonNullChecks = variables
|
1150 | .filter(f => graphql.isNonNullType(f))
|
1151 | .map(f => `Utils.checkNotNull(${f.variable.name.value}, "${f.variable.name.value} == null");`);
|
1152 | const returnStatement = `return new ${parentClassName}(${variables.map(v => v.variable.name.value).join(', ')});`;
|
1153 | cls.addClassMethod('build', parentClassName, `${[...nonNullChecks, returnStatement].join('\n')}`, [], [], 'public');
|
1154 | return cls;
|
1155 | }
|
1156 | }
|
1157 |
|
1158 | var FileType;
|
1159 | (function (FileType) {
|
1160 | FileType[FileType["INPUT_TYPE"] = 0] = "INPUT_TYPE";
|
1161 | FileType[FileType["OPERATION"] = 1] = "OPERATION";
|
1162 | FileType[FileType["FRAGMENT"] = 2] = "FRAGMENT";
|
1163 | FileType[FileType["CUSTOM_TYPES"] = 3] = "CUSTOM_TYPES";
|
1164 | })(FileType || (FileType = {}));
|
1165 |
|
1166 | const filteredScalars = ['String', 'Float', 'Int', 'Boolean'];
|
1167 | class CustomTypeClassVisitor extends BaseJavaVisitor {
|
1168 | constructor(schema, rawConfig) {
|
1169 | super(schema, rawConfig, {
|
1170 | typePackage: rawConfig.typePackage || 'type',
|
1171 | });
|
1172 | }
|
1173 | extract(name) {
|
1174 | const lastIndex = name.lastIndexOf('.');
|
1175 | if (lastIndex === -1) {
|
1176 | return {
|
1177 | className: name,
|
1178 | importFrom: Imports[name] || null,
|
1179 | };
|
1180 | }
|
1181 | else {
|
1182 | return {
|
1183 | className: name.substring(lastIndex + 1),
|
1184 | importFrom: name,
|
1185 | };
|
1186 | }
|
1187 | }
|
1188 | additionalContent() {
|
1189 | this._imports.add(Imports.ScalarType);
|
1190 | this._imports.add(Imports.Class);
|
1191 | this._imports.add(Imports.Override);
|
1192 | this._imports.add(Imports.Generated);
|
1193 | const allTypes = this._schema.getTypeMap();
|
1194 | const enumValues = Object.keys(allTypes)
|
1195 | .filter(t => graphql.isScalarType(allTypes[t]) && !filteredScalars.includes(t))
|
1196 | .map(t => allTypes[t])
|
1197 | .map(scalarType => {
|
1198 | const uppercaseName = scalarType.name.toUpperCase();
|
1199 | const javaType = this.extract(this.scalars[scalarType.name] || 'String');
|
1200 | if (javaType.importFrom) {
|
1201 | this._imports.add(javaType.importFrom);
|
1202 | }
|
1203 | return visitorPluginCommon.indentMultiline(`${uppercaseName} {
|
1204 | @Override
|
1205 | public String typeName() {
|
1206 | return "${scalarType.name}";
|
1207 | }
|
1208 |
|
1209 | @Override
|
1210 | public Class javaType() {
|
1211 | return ${javaType.className}.class;
|
1212 | }
|
1213 | }`);
|
1214 | })
|
1215 | .join(',\n\n');
|
1216 | return new javaCommon.JavaDeclarationBlock()
|
1217 | .annotate([`Generated("Apollo GraphQL")`])
|
1218 | .access('public')
|
1219 | .asKind('enum')
|
1220 | .withName('CustomType')
|
1221 | .implements(['ScalarType'])
|
1222 | .withBlock(enumValues).string;
|
1223 | }
|
1224 | getPackage() {
|
1225 | return this.config.typePackage;
|
1226 | }
|
1227 | }
|
1228 |
|
1229 | const plugin = (schema, documents, config) => {
|
1230 | const allAst = graphql.concatAST(documents.map(v => v.document));
|
1231 | const allFragments = [
|
1232 | ...allAst.definitions.filter(d => d.kind === graphql.Kind.FRAGMENT_DEFINITION).map(fragmentDef => ({
|
1233 | node: fragmentDef,
|
1234 | name: fragmentDef.name.value,
|
1235 | onType: fragmentDef.typeCondition.name.value,
|
1236 | isExternal: false,
|
1237 | })),
|
1238 | ...(config.externalFragments || []),
|
1239 | ];
|
1240 | let visitor;
|
1241 | switch (config.fileType) {
|
1242 | case FileType.FRAGMENT:
|
1243 | case FileType.OPERATION: {
|
1244 | visitor = new OperationVisitor(schema, config, allFragments);
|
1245 | break;
|
1246 | }
|
1247 | case FileType.INPUT_TYPE: {
|
1248 | visitor = new InputTypeVisitor(schema, config);
|
1249 | break;
|
1250 | }
|
1251 | case FileType.CUSTOM_TYPES: {
|
1252 | visitor = new CustomTypeClassVisitor(schema, config);
|
1253 | break;
|
1254 | }
|
1255 | }
|
1256 | if (!visitor) {
|
1257 | return { content: '' };
|
1258 | }
|
1259 | const visitResult = graphql.visit(allAst, visitor);
|
1260 | const additionalContent = visitor.additionalContent();
|
1261 | const imports = visitor.getImports();
|
1262 | return {
|
1263 | prepend: [`package ${visitor.getPackage()};\n`, ...imports],
|
1264 | content: '\n' + [...visitResult.definitions.filter(a => a && typeof a === 'string'), additionalContent].join('\n'),
|
1265 | };
|
1266 | };
|
1267 |
|
1268 | const packageNameToDirectory = (packageName) => {
|
1269 | return `./${packageName.split('.').join('/')}/`;
|
1270 | };
|
1271 | const preset = {
|
1272 | buildGeneratesSection: options => {
|
1273 | const outDir = options.baseOutputDir;
|
1274 | const inputTypesAst = [];
|
1275 | graphql.visit(options.schema, {
|
1276 | enter: {
|
1277 | InputObjectTypeDefinition(node) {
|
1278 | inputTypesAst.push(node);
|
1279 | },
|
1280 | },
|
1281 | });
|
1282 | const inputTypesDocumentNode = { kind: graphql.Kind.DOCUMENT, definitions: inputTypesAst };
|
1283 | const allAst = graphql.concatAST(options.documents.map(v => v.document));
|
1284 | const operationsAst = allAst.definitions.filter(d => d.kind === graphql.Kind.OPERATION_DEFINITION);
|
1285 | const fragments = allAst.definitions.filter(d => d.kind === graphql.Kind.FRAGMENT_DEFINITION);
|
1286 | const externalFragments = fragments.map(frag => ({
|
1287 | isExternal: true,
|
1288 | importFrom: frag.name.value,
|
1289 | name: frag.name.value,
|
1290 | onType: frag.typeCondition.name.value,
|
1291 | node: frag,
|
1292 | }));
|
1293 | return [
|
1294 | {
|
1295 | filename: path.join(outDir, packageNameToDirectory(options.config.typePackage), 'CustomType.java'),
|
1296 | plugins: options.plugins,
|
1297 | pluginMap: options.pluginMap,
|
1298 | config: {
|
1299 | ...options.config,
|
1300 | fileType: FileType.CUSTOM_TYPES,
|
1301 | },
|
1302 | schema: options.schema,
|
1303 | documents: [],
|
1304 | },
|
1305 | ...inputTypesDocumentNode.definitions.map((ast) => {
|
1306 | return {
|
1307 | filename: path.join(outDir, packageNameToDirectory(options.config.typePackage), ast.name.value + '.java'),
|
1308 | plugins: options.plugins,
|
1309 | pluginMap: options.pluginMap,
|
1310 | config: {
|
1311 | ...options.config,
|
1312 | fileType: FileType.INPUT_TYPE,
|
1313 | skipDocumentsValidation: true,
|
1314 | },
|
1315 | schema: options.schema,
|
1316 | documents: [{ document: { kind: graphql.Kind.DOCUMENT, definitions: [ast] }, location: '' }],
|
1317 | };
|
1318 | }),
|
1319 | ...operationsAst.map((ast) => {
|
1320 | const fileName = ast.name.value.toLowerCase().endsWith(ast.operation)
|
1321 | ? ast.name.value
|
1322 | : `${ast.name.value}${pascalCase.pascalCase(ast.operation)}`;
|
1323 | return {
|
1324 | filename: path.join(outDir, packageNameToDirectory(options.config.package), fileName + '.java'),
|
1325 | plugins: options.plugins,
|
1326 | pluginMap: options.pluginMap,
|
1327 | config: {
|
1328 | ...options.config,
|
1329 | fileType: FileType.OPERATION,
|
1330 | externalFragments,
|
1331 | },
|
1332 | schema: options.schema,
|
1333 | documents: [{ document: { kind: graphql.Kind.DOCUMENT, definitions: [ast] }, location: '' }],
|
1334 | };
|
1335 | }),
|
1336 | ...fragments.map((ast) => {
|
1337 | return {
|
1338 | filename: path.join(outDir, packageNameToDirectory(options.config.fragmentPackage), ast.name.value + '.java'),
|
1339 | plugins: options.plugins,
|
1340 | pluginMap: options.pluginMap,
|
1341 | config: {
|
1342 | ...options.config,
|
1343 | fileType: FileType.FRAGMENT,
|
1344 | externalFragments,
|
1345 | },
|
1346 | schema: options.schema,
|
1347 | documents: [{ document: { kind: graphql.Kind.DOCUMENT, definitions: [ast] }, location: '' }],
|
1348 | };
|
1349 | }),
|
1350 | ];
|
1351 | },
|
1352 | };
|
1353 |
|
1354 | exports.plugin = plugin;
|
1355 | exports.preset = preset;
|
1356 |
|