1 | import path from "path";
|
2 |
|
3 | import {
|
4 | GraphQLError,
|
5 | GraphQLType,
|
6 | getNamedType,
|
7 | isCompositeType,
|
8 | GraphQLEnumType,
|
9 | GraphQLInputObjectType,
|
10 | isNonNullType,
|
11 | isListType,
|
12 | isEnumType,
|
13 | isInputObjectType
|
14 | } from "graphql";
|
15 |
|
16 | import {
|
17 | CompilerContext,
|
18 | Operation,
|
19 | Fragment,
|
20 | SelectionSet,
|
21 | Field
|
22 | } from "apollo-codegen-core/lib/compiler";
|
23 |
|
24 | import {
|
25 | SwiftGenerator,
|
26 | Property,
|
27 | Struct,
|
28 | SwiftSource,
|
29 | swift
|
30 | } from "./language";
|
31 | import { Helpers } from "./helpers";
|
32 | import { isList } from "apollo-codegen-core/lib/utilities/graphql";
|
33 |
|
34 | import {
|
35 | typeCaseForSelectionSet,
|
36 | TypeCase,
|
37 | Variant
|
38 | } from "apollo-codegen-core/lib/compiler/visitors/typeCase";
|
39 | import { collectFragmentsReferenced } from "apollo-codegen-core/lib/compiler/visitors/collectFragmentsReferenced";
|
40 | import { generateOperationId } from "apollo-codegen-core/lib/compiler/visitors/generateOperationId";
|
41 | import { collectAndMergeFields } from "apollo-codegen-core/lib/compiler/visitors/collectAndMergeFields";
|
42 |
|
43 | import "apollo-codegen-core/lib/utilities/array";
|
44 |
|
45 | const { join, wrap } = SwiftSource;
|
46 |
|
47 | export interface Options {
|
48 | namespace?: string;
|
49 | passthroughCustomScalars?: boolean;
|
50 | customScalarsPrefix?: string;
|
51 | }
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 | export function generateSource(
|
63 | context: CompilerContext,
|
64 | outputIndividualFiles: boolean,
|
65 | suppressMultilineStringLiterals: boolean,
|
66 | only?: string
|
67 | ): SwiftAPIGenerator {
|
68 | const generator = new SwiftAPIGenerator(context);
|
69 |
|
70 | if (outputIndividualFiles) {
|
71 | generator.withinFile(`Types.graphql.swift`, () => {
|
72 | generator.fileHeader();
|
73 |
|
74 | generator.namespaceDeclaration(context.options.namespace, () => {
|
75 | context.typesUsed.forEach(type => {
|
76 | generator.typeDeclarationForGraphQLType(type, true);
|
77 | });
|
78 | });
|
79 | });
|
80 |
|
81 | const inputFilePaths = new Set<string>();
|
82 |
|
83 | Object.values(context.operations).forEach(operation => {
|
84 | inputFilePaths.add(operation.filePath);
|
85 | });
|
86 |
|
87 | Object.values(context.fragments).forEach(fragment => {
|
88 | inputFilePaths.add(fragment.filePath);
|
89 | });
|
90 |
|
91 | for (const inputFilePath of inputFilePaths) {
|
92 | if (only && inputFilePath !== only) continue;
|
93 |
|
94 | generator.withinFile(`${path.basename(inputFilePath)}.swift`, () => {
|
95 | generator.fileHeader();
|
96 |
|
97 | generator.namespaceExtensionDeclaration(
|
98 | context.options.namespace,
|
99 | () => {
|
100 | Object.values(context.operations).forEach(operation => {
|
101 | if (operation.filePath === inputFilePath) {
|
102 | generator.classDeclarationForOperation(
|
103 | operation,
|
104 | true,
|
105 | suppressMultilineStringLiterals
|
106 | );
|
107 | }
|
108 | });
|
109 |
|
110 | Object.values(context.fragments).forEach(fragment => {
|
111 | if (fragment.filePath === inputFilePath) {
|
112 | generator.structDeclarationForFragment(
|
113 | fragment,
|
114 | true,
|
115 | suppressMultilineStringLiterals
|
116 | );
|
117 | }
|
118 | });
|
119 | }
|
120 | );
|
121 | });
|
122 | }
|
123 | } else {
|
124 | generator.fileHeader();
|
125 |
|
126 | generator.namespaceDeclaration(context.options.namespace, () => {
|
127 | context.typesUsed.forEach(type => {
|
128 | generator.typeDeclarationForGraphQLType(type, false);
|
129 | });
|
130 |
|
131 | Object.values(context.operations).forEach(operation => {
|
132 | generator.classDeclarationForOperation(
|
133 | operation,
|
134 | false,
|
135 | suppressMultilineStringLiterals
|
136 | );
|
137 | });
|
138 |
|
139 | Object.values(context.fragments).forEach(fragment => {
|
140 | generator.structDeclarationForFragment(
|
141 | fragment,
|
142 | false,
|
143 | suppressMultilineStringLiterals
|
144 | );
|
145 | });
|
146 | });
|
147 | }
|
148 |
|
149 | return generator;
|
150 | }
|
151 |
|
152 | export class SwiftAPIGenerator extends SwiftGenerator<CompilerContext> {
|
153 | helpers: Helpers;
|
154 |
|
155 | constructor(context: CompilerContext) {
|
156 | super(context);
|
157 |
|
158 | this.helpers = new Helpers(context.options);
|
159 | }
|
160 |
|
161 | fileHeader() {
|
162 | this.printOnNewline(SwiftSource.raw`// @generated`);
|
163 | this.printOnNewline(
|
164 | SwiftSource.raw`// This file was automatically generated and should not be edited.`
|
165 | );
|
166 | this.printNewline();
|
167 | this.printOnNewline(swift`import Apollo`);
|
168 | this.printOnNewline(swift`import Foundation`);
|
169 | }
|
170 |
|
171 | |
172 |
|
173 |
|
174 |
|
175 |
|
176 |
|
177 |
|
178 | classDeclarationForOperation(
|
179 | operation: Operation,
|
180 | outputIndividualFiles: boolean,
|
181 | suppressMultilineStringLiterals: boolean
|
182 | ) {
|
183 | const {
|
184 | operationName,
|
185 | operationType,
|
186 | variables,
|
187 | source,
|
188 | selectionSet
|
189 | } = operation;
|
190 |
|
191 | let className;
|
192 | let protocol;
|
193 |
|
194 | switch (operationType) {
|
195 | case "query":
|
196 | className = `${this.helpers.operationClassName(operationName)}Query`;
|
197 | protocol = "GraphQLQuery";
|
198 | break;
|
199 | case "mutation":
|
200 | className = `${this.helpers.operationClassName(operationName)}Mutation`;
|
201 | protocol = "GraphQLMutation";
|
202 | break;
|
203 | case "subscription":
|
204 | className = `${this.helpers.operationClassName(
|
205 | operationName
|
206 | )}Subscription`;
|
207 | protocol = "GraphQLSubscription";
|
208 | break;
|
209 | default:
|
210 | throw new GraphQLError(`Unsupported operation type "${operationType}"`);
|
211 | }
|
212 |
|
213 | const {
|
214 | options: { namespace },
|
215 | fragments
|
216 | } = this.context;
|
217 | const isRedundant = !!namespace && outputIndividualFiles;
|
218 | const modifiers = isRedundant ? ["final"] : ["public", "final"];
|
219 |
|
220 | this.classDeclaration(
|
221 | {
|
222 | className,
|
223 | modifiers,
|
224 | adoptedProtocols: [protocol]
|
225 | },
|
226 | () => {
|
227 | if (source) {
|
228 | this.comment("The raw GraphQL definition of this operation.");
|
229 | this.printOnNewline(swift`public let operationDefinition: String =`);
|
230 | this.withIndent(() => {
|
231 | this.multilineString(source, suppressMultilineStringLiterals);
|
232 | });
|
233 | }
|
234 |
|
235 | this.printNewlineIfNeeded();
|
236 | this.printOnNewline(
|
237 | swift`public let operationName: String = ${SwiftSource.string(
|
238 | operationName
|
239 | )}`
|
240 | );
|
241 |
|
242 | const fragmentsReferenced = collectFragmentsReferenced(
|
243 | operation.selectionSet,
|
244 | fragments
|
245 | );
|
246 |
|
247 | if (this.context.options.generateOperationIds) {
|
248 | const { operationId, sourceWithFragments } = generateOperationId(
|
249 | operation,
|
250 | fragments,
|
251 | fragmentsReferenced
|
252 | );
|
253 | operation.operationId = operationId;
|
254 | operation.sourceWithFragments = sourceWithFragments;
|
255 | this.printNewlineIfNeeded();
|
256 | this.printOnNewline(
|
257 | swift`public let operationIdentifier: String? = ${SwiftSource.string(
|
258 | operationId
|
259 | )}`
|
260 | );
|
261 | }
|
262 |
|
263 | if (fragmentsReferenced.size > 0) {
|
264 | this.printNewlineIfNeeded();
|
265 | this.printOnNewline(swift`public var queryDocument: String`);
|
266 | this.withinBlock(() => {
|
267 | this.printOnNewline(
|
268 | swift`var document: String = operationDefinition`
|
269 | );
|
270 | fragmentsReferenced.forEach(fragmentName => {
|
271 | this.printOnNewline(
|
272 | swift`document.append("\\n" + ${this.helpers.structNameForFragmentName(
|
273 | fragmentName
|
274 | )}.fragmentDefinition)`
|
275 | );
|
276 | });
|
277 | this.printOnNewline(swift`return document`);
|
278 | });
|
279 | }
|
280 |
|
281 | this.printNewlineIfNeeded();
|
282 |
|
283 | if (variables && variables.length > 0) {
|
284 | const properties = variables.map(({ name, type }) => {
|
285 | const typeName = this.helpers.typeNameFromGraphQLType(type);
|
286 | const isOptional = !(
|
287 | isNonNullType(type) ||
|
288 | (isListType(type) && isNonNullType(type.ofType))
|
289 | );
|
290 | return { name, propertyName: name, type, typeName, isOptional };
|
291 | });
|
292 |
|
293 | this.propertyDeclarations(properties);
|
294 |
|
295 | this.printNewlineIfNeeded();
|
296 | this.initializerDeclarationForProperties(properties);
|
297 |
|
298 | this.printNewlineIfNeeded();
|
299 | this.printOnNewline(swift`public var variables: GraphQLMap?`);
|
300 | this.withinBlock(() => {
|
301 | this.printOnNewline(
|
302 | wrap(
|
303 | swift`return [`,
|
304 | join(
|
305 | properties.map(
|
306 | ({ name, propertyName }) =>
|
307 | swift`${SwiftSource.string(name)}: ${propertyName}`
|
308 | ),
|
309 | ", "
|
310 | ) || swift`:`,
|
311 | swift`]`
|
312 | )
|
313 | );
|
314 | });
|
315 | } else {
|
316 | this.initializerDeclarationForProperties([]);
|
317 | }
|
318 |
|
319 | this.structDeclarationForSelectionSet(
|
320 | {
|
321 | structName: "Data",
|
322 | selectionSet
|
323 | },
|
324 | outputIndividualFiles
|
325 | );
|
326 | }
|
327 | );
|
328 | }
|
329 |
|
330 | |
331 |
|
332 |
|
333 |
|
334 |
|
335 |
|
336 |
|
337 | structDeclarationForFragment(
|
338 | { fragmentName, selectionSet, source }: Fragment,
|
339 | outputIndividualFiles: boolean,
|
340 | suppressMultilineStringLiterals: boolean
|
341 | ) {
|
342 | const structName = this.helpers.structNameForFragmentName(fragmentName);
|
343 |
|
344 | this.structDeclarationForSelectionSet(
|
345 | {
|
346 | structName,
|
347 | adoptedProtocols: ["GraphQLFragment"],
|
348 | selectionSet
|
349 | },
|
350 | outputIndividualFiles,
|
351 | () => {
|
352 | if (source) {
|
353 | this.comment("The raw GraphQL definition of this fragment.");
|
354 | this.printOnNewline(
|
355 | swift`public static let fragmentDefinition: String =`
|
356 | );
|
357 | this.withIndent(() => {
|
358 | this.multilineString(source, suppressMultilineStringLiterals);
|
359 | });
|
360 | }
|
361 | }
|
362 | );
|
363 | }
|
364 |
|
365 | |
366 |
|
367 |
|
368 |
|
369 |
|
370 |
|
371 |
|
372 |
|
373 | structDeclarationForSelectionSet(
|
374 | {
|
375 | structName,
|
376 | adoptedProtocols = ["GraphQLSelectionSet"],
|
377 | selectionSet
|
378 | }: {
|
379 | structName: string;
|
380 | adoptedProtocols?: string[];
|
381 | selectionSet: SelectionSet;
|
382 | },
|
383 | outputIndividualFiles: boolean,
|
384 | before?: Function
|
385 | ) {
|
386 | const typeCase = typeCaseForSelectionSet(
|
387 | selectionSet,
|
388 | !!this.context.options.mergeInFieldsFromFragmentSpreads
|
389 | );
|
390 |
|
391 | this.structDeclarationForVariant(
|
392 | {
|
393 | structName,
|
394 | adoptedProtocols,
|
395 | variant: typeCase.default,
|
396 | typeCase
|
397 | },
|
398 | outputIndividualFiles,
|
399 | before,
|
400 | () => {
|
401 | const variants = typeCase.variants.map(
|
402 | this.helpers.propertyFromVariant,
|
403 | this.helpers
|
404 | );
|
405 |
|
406 | for (const variant of variants) {
|
407 | this.propertyDeclarationForVariant(variant);
|
408 |
|
409 | this.structDeclarationForVariant(
|
410 | {
|
411 | structName: variant.structName,
|
412 | variant
|
413 | },
|
414 | outputIndividualFiles
|
415 | );
|
416 | }
|
417 | }
|
418 | );
|
419 | }
|
420 |
|
421 | |
422 |
|
423 |
|
424 |
|
425 |
|
426 |
|
427 |
|
428 |
|
429 |
|
430 | structDeclarationForVariant(
|
431 | {
|
432 | structName,
|
433 | adoptedProtocols = ["GraphQLSelectionSet"],
|
434 | variant,
|
435 | typeCase
|
436 | }: {
|
437 | structName: string;
|
438 | adoptedProtocols?: string[];
|
439 | variant: Variant;
|
440 | typeCase?: TypeCase;
|
441 | },
|
442 | outputIndividualFiles: boolean,
|
443 | before?: Function,
|
444 | after?: Function
|
445 | ) {
|
446 | const {
|
447 | options: {
|
448 | namespace,
|
449 | mergeInFieldsFromFragmentSpreads,
|
450 | omitDeprecatedEnumCases
|
451 | }
|
452 | } = this.context;
|
453 |
|
454 | this.structDeclaration(
|
455 | { structName, adoptedProtocols, namespace },
|
456 | outputIndividualFiles,
|
457 | () => {
|
458 | if (before) {
|
459 | before();
|
460 | }
|
461 |
|
462 | this.printNewlineIfNeeded();
|
463 | this.printOnNewline(
|
464 | swift`public static let possibleTypes: [String] = [`
|
465 | );
|
466 | this.print(
|
467 | join(
|
468 | variant.possibleTypes.map(
|
469 | type => swift`${SwiftSource.string(type.name)}`
|
470 | ),
|
471 | ", "
|
472 | )
|
473 | );
|
474 | this.print(swift`]`);
|
475 |
|
476 | this.printNewlineIfNeeded();
|
477 | this.printOnNewline(
|
478 | swift`public static var selections: [GraphQLSelection] {`
|
479 | );
|
480 | this.withIndent(() => {
|
481 | this.printOnNewline(swift`return `);
|
482 | if (typeCase) {
|
483 | this.typeCaseInitialization(typeCase);
|
484 | } else {
|
485 | this.selectionSetInitialization(variant);
|
486 | }
|
487 | });
|
488 | this.printOnNewline(swift`}`);
|
489 | this.printNewlineIfNeeded();
|
490 |
|
491 | this.printOnNewline(
|
492 | swift`public private(set) var resultMap: ResultMap`
|
493 | );
|
494 |
|
495 | this.printNewlineIfNeeded();
|
496 | this.printOnNewline(swift`public init(unsafeResultMap: ResultMap)`);
|
497 | this.withinBlock(() => {
|
498 | this.printOnNewline(swift`self.resultMap = unsafeResultMap`);
|
499 | });
|
500 |
|
501 | if (typeCase) {
|
502 | this.initializersForTypeCase(typeCase);
|
503 | } else {
|
504 | this.initializersForVariant(variant);
|
505 | }
|
506 |
|
507 | const fields = collectAndMergeFields(
|
508 | variant,
|
509 | !!mergeInFieldsFromFragmentSpreads
|
510 | ).map(field => this.helpers.propertyFromField(field as Field));
|
511 |
|
512 | const fragmentSpreads = variant.fragmentSpreads.map(fragmentSpread => {
|
513 | const isConditional = variant.possibleTypes.some(
|
514 | type => !fragmentSpread.selectionSet.possibleTypes.includes(type)
|
515 | );
|
516 |
|
517 | return this.helpers.propertyFromFragmentSpread(
|
518 | fragmentSpread,
|
519 | isConditional
|
520 | );
|
521 | });
|
522 |
|
523 | fields.forEach(this.propertyDeclarationForField, this);
|
524 |
|
525 | if (fragmentSpreads.length > 0) {
|
526 | this.printNewlineIfNeeded();
|
527 | this.printOnNewline(swift`public var fragments: Fragments`);
|
528 | this.withinBlock(() => {
|
529 | this.printOnNewline(swift`get`);
|
530 | this.withinBlock(() => {
|
531 | this.printOnNewline(
|
532 | swift`return Fragments(unsafeResultMap: resultMap)`
|
533 | );
|
534 | });
|
535 | this.printOnNewline(swift`set`);
|
536 | this.withinBlock(() => {
|
537 | this.printOnNewline(swift`resultMap += newValue.resultMap`);
|
538 | });
|
539 | });
|
540 |
|
541 | this.structDeclaration(
|
542 | {
|
543 | structName: "Fragments"
|
544 | },
|
545 | outputIndividualFiles,
|
546 | () => {
|
547 | this.printOnNewline(
|
548 | swift`public private(set) var resultMap: ResultMap`
|
549 | );
|
550 |
|
551 | this.printNewlineIfNeeded();
|
552 | this.printOnNewline(
|
553 | swift`public init(unsafeResultMap: ResultMap)`
|
554 | );
|
555 | this.withinBlock(() => {
|
556 | this.printOnNewline(swift`self.resultMap = unsafeResultMap`);
|
557 | });
|
558 |
|
559 | for (const fragmentSpread of fragmentSpreads) {
|
560 | const {
|
561 | propertyName,
|
562 | typeName,
|
563 | structName,
|
564 | isConditional
|
565 | } = fragmentSpread;
|
566 |
|
567 | this.printNewlineIfNeeded();
|
568 | this.printOnNewline(
|
569 | swift`public var ${propertyName}: ${typeName}`
|
570 | );
|
571 | this.withinBlock(() => {
|
572 | this.printOnNewline(swift`get`);
|
573 | this.withinBlock(() => {
|
574 | if (isConditional) {
|
575 | this.printOnNewline(
|
576 | swift`if !${structName}.possibleTypes.contains(resultMap["__typename"]! as! String) { return nil }`
|
577 | );
|
578 | }
|
579 | this.printOnNewline(
|
580 | swift`return ${structName}(unsafeResultMap: resultMap)`
|
581 | );
|
582 | });
|
583 | this.printOnNewline(swift`set`);
|
584 | this.withinBlock(() => {
|
585 | if (isConditional) {
|
586 | this.printOnNewline(
|
587 | swift`guard let newValue = newValue else { return }`
|
588 | );
|
589 | this.printOnNewline(
|
590 | swift`resultMap += newValue.resultMap`
|
591 | );
|
592 | } else {
|
593 | this.printOnNewline(
|
594 | swift`resultMap += newValue.resultMap`
|
595 | );
|
596 | }
|
597 | });
|
598 | });
|
599 | }
|
600 | }
|
601 | );
|
602 | }
|
603 |
|
604 | for (const field of fields) {
|
605 | if (isCompositeType(getNamedType(field.type)) && field.selectionSet) {
|
606 | this.structDeclarationForSelectionSet(
|
607 | {
|
608 | structName: field.structName,
|
609 | selectionSet: field.selectionSet
|
610 | },
|
611 | outputIndividualFiles
|
612 | );
|
613 | }
|
614 | }
|
615 |
|
616 | if (after) {
|
617 | after();
|
618 | }
|
619 | }
|
620 | );
|
621 | }
|
622 |
|
623 | initializersForTypeCase(typeCase: TypeCase) {
|
624 | const variants = typeCase.variants;
|
625 |
|
626 | if (variants.length == 0) {
|
627 | this.initializersForVariant(typeCase.default);
|
628 | } else {
|
629 | const remainder = typeCase.remainder;
|
630 | for (const variant of remainder ? [remainder, ...variants] : variants) {
|
631 | this.initializersForVariant(
|
632 | variant,
|
633 | variant === remainder
|
634 | ? undefined
|
635 | : this.helpers.structNameForVariant(variant),
|
636 | false
|
637 | );
|
638 | }
|
639 | }
|
640 | }
|
641 |
|
642 | initializersForVariant(
|
643 | variant: Variant,
|
644 | namespace?: string,
|
645 | useInitializerIfPossible: boolean = true
|
646 | ) {
|
647 | if (useInitializerIfPossible && variant.possibleTypes.length == 1) {
|
648 | const properties = this.helpers.propertiesForSelectionSet(variant);
|
649 | if (!properties) return;
|
650 |
|
651 | this.printNewlineIfNeeded();
|
652 | this.printOnNewline(swift`public init`);
|
653 |
|
654 | this.parametersForProperties(properties);
|
655 |
|
656 | this.withinBlock(() => {
|
657 | this.printOnNewline(
|
658 | wrap(
|
659 | swift`self.init(unsafeResultMap: [`,
|
660 | join(
|
661 | [
|
662 | swift`"__typename": ${SwiftSource.string(
|
663 | variant.possibleTypes[0].toString()
|
664 | )}`,
|
665 | ...properties.map(p =>
|
666 | this.propertyAssignmentForField(p, properties)
|
667 | )
|
668 | ],
|
669 | ", "
|
670 | ) || swift`:`,
|
671 | swift`])`
|
672 | )
|
673 | );
|
674 | });
|
675 | } else {
|
676 | const structName = this.scope.typeName;
|
677 |
|
678 | for (const possibleType of variant.possibleTypes) {
|
679 | const properties = this.helpers.propertiesForSelectionSet(
|
680 | {
|
681 | possibleTypes: [possibleType],
|
682 | selections: variant.selections
|
683 | },
|
684 | namespace
|
685 | );
|
686 |
|
687 | if (!properties) continue;
|
688 |
|
689 | this.printNewlineIfNeeded();
|
690 | this.printOnNewline(
|
691 | SwiftSource.raw`public static func make${possibleType}`
|
692 | );
|
693 |
|
694 | this.parametersForProperties(properties);
|
695 |
|
696 | this.print(swift` -> ${structName}`);
|
697 |
|
698 | this.withinBlock(() => {
|
699 | this.printOnNewline(
|
700 | wrap(
|
701 | swift`return ${structName}(unsafeResultMap: [`,
|
702 | join(
|
703 | [
|
704 | swift`"__typename": ${SwiftSource.string(
|
705 | possibleType.toString()
|
706 | )}`,
|
707 | ...properties.map(p =>
|
708 | this.propertyAssignmentForField(p, properties)
|
709 | )
|
710 | ],
|
711 | ", "
|
712 | ) || swift`:`,
|
713 | swift`])`
|
714 | )
|
715 | );
|
716 | });
|
717 | }
|
718 | }
|
719 | }
|
720 |
|
721 | propertyAssignmentForField(
|
722 | field: {
|
723 | responseKey: string;
|
724 | propertyName: string;
|
725 | type: GraphQLType;
|
726 | isConditional?: boolean;
|
727 | structName?: string;
|
728 | },
|
729 | properties: { propertyName: string }[]
|
730 | ): SwiftSource {
|
731 | const {
|
732 | responseKey,
|
733 | propertyName,
|
734 | type,
|
735 | isConditional,
|
736 | structName
|
737 | } = field;
|
738 | const parameterName = this.helpers.internalParameterName(
|
739 | propertyName,
|
740 | properties
|
741 | );
|
742 | const valueExpression = isCompositeType(getNamedType(type))
|
743 | ? this.helpers.mapExpressionForType(
|
744 | type,
|
745 | isConditional,
|
746 | expression => swift`${expression}.resultMap`,
|
747 | SwiftSource.identifier(parameterName),
|
748 | structName!,
|
749 | "ResultMap"
|
750 | )
|
751 | : SwiftSource.identifier(parameterName);
|
752 | return swift`${SwiftSource.string(responseKey)}: ${valueExpression}`;
|
753 | }
|
754 |
|
755 | propertyDeclarationForField(field: Field & Property) {
|
756 | const {
|
757 | responseKey,
|
758 | propertyName,
|
759 | typeName,
|
760 | type,
|
761 | isOptional,
|
762 | isConditional
|
763 | } = field;
|
764 |
|
765 | const unmodifiedFieldType = getNamedType(type);
|
766 |
|
767 | this.printNewlineIfNeeded();
|
768 |
|
769 | this.comment(field.description);
|
770 | this.deprecationAttributes(field.isDeprecated, field.deprecationReason);
|
771 |
|
772 | this.printOnNewline(swift`public var ${propertyName}: ${typeName}`);
|
773 | this.withinBlock(() => {
|
774 | if (isCompositeType(unmodifiedFieldType)) {
|
775 | const structName = this.helpers.structNameForPropertyName(responseKey);
|
776 |
|
777 | if (isList(type)) {
|
778 | this.printOnNewline(swift`get`);
|
779 | this.withinBlock(() => {
|
780 | const resultMapTypeName = this.helpers.typeNameFromGraphQLType(
|
781 | type,
|
782 | "ResultMap",
|
783 | false
|
784 | );
|
785 | let expression;
|
786 | if (isOptional) {
|
787 | expression = swift`(resultMap[${SwiftSource.string(
|
788 | responseKey
|
789 | )}] as? ${resultMapTypeName})`;
|
790 | } else {
|
791 | expression = swift`(resultMap[${SwiftSource.string(
|
792 | responseKey
|
793 | )}] as! ${resultMapTypeName})`;
|
794 | }
|
795 | this.printOnNewline(
|
796 | swift`return ${this.helpers.mapExpressionForType(
|
797 | type,
|
798 | isConditional,
|
799 | expression =>
|
800 | swift`${structName}(unsafeResultMap: ${expression})`,
|
801 | expression,
|
802 | "ResultMap",
|
803 | structName
|
804 | )}`
|
805 | );
|
806 | });
|
807 | this.printOnNewline(swift`set`);
|
808 | this.withinBlock(() => {
|
809 | let newValueExpression = this.helpers.mapExpressionForType(
|
810 | type,
|
811 | isConditional,
|
812 | expression => swift`${expression}.resultMap`,
|
813 | swift`newValue`,
|
814 | structName,
|
815 | "ResultMap"
|
816 | );
|
817 | this.printOnNewline(
|
818 | swift`resultMap.updateValue(${newValueExpression}, forKey: ${SwiftSource.string(
|
819 | responseKey
|
820 | )})`
|
821 | );
|
822 | });
|
823 | } else {
|
824 | this.printOnNewline(swift`get`);
|
825 | this.withinBlock(() => {
|
826 | if (isOptional) {
|
827 | this.printOnNewline(
|
828 | swift`return (resultMap[${SwiftSource.string(
|
829 | responseKey
|
830 | )}] as? ResultMap).flatMap { ${structName}(unsafeResultMap: $0) }`
|
831 | );
|
832 | } else {
|
833 | this.printOnNewline(
|
834 | swift`return ${structName}(unsafeResultMap: resultMap[${SwiftSource.string(
|
835 | responseKey
|
836 | )}]! as! ResultMap)`
|
837 | );
|
838 | }
|
839 | });
|
840 | this.printOnNewline(swift`set`);
|
841 | this.withinBlock(() => {
|
842 | let newValueExpression;
|
843 | if (isOptional) {
|
844 | newValueExpression = "newValue?.resultMap";
|
845 | } else {
|
846 | newValueExpression = "newValue.resultMap";
|
847 | }
|
848 | this.printOnNewline(
|
849 | swift`resultMap.updateValue(${newValueExpression}, forKey: ${SwiftSource.string(
|
850 | responseKey
|
851 | )})`
|
852 | );
|
853 | });
|
854 | }
|
855 | } else {
|
856 | this.printOnNewline(swift`get`);
|
857 | this.withinBlock(() => {
|
858 | if (isOptional) {
|
859 | this.printOnNewline(
|
860 | swift`return resultMap[${SwiftSource.string(
|
861 | responseKey
|
862 | )}] as? ${typeName.slice(0, -1)}`
|
863 | );
|
864 | } else {
|
865 | this.printOnNewline(
|
866 | swift`return resultMap[${SwiftSource.string(
|
867 | responseKey
|
868 | )}]! as! ${typeName}`
|
869 | );
|
870 | }
|
871 | });
|
872 | this.printOnNewline(swift`set`);
|
873 | this.withinBlock(() => {
|
874 | this.printOnNewline(
|
875 | swift`resultMap.updateValue(newValue, forKey: ${SwiftSource.string(
|
876 | responseKey
|
877 | )})`
|
878 | );
|
879 | });
|
880 | }
|
881 | });
|
882 | }
|
883 |
|
884 | propertyDeclarationForVariant(variant: Property & Struct) {
|
885 | const { propertyName, typeName, structName } = variant;
|
886 |
|
887 | this.printNewlineIfNeeded();
|
888 | this.printOnNewline(swift`public var ${propertyName}: ${typeName}`);
|
889 | this.withinBlock(() => {
|
890 | this.printOnNewline(swift`get`);
|
891 | this.withinBlock(() => {
|
892 | this.printOnNewline(
|
893 | swift`if !${structName}.possibleTypes.contains(__typename) { return nil }`
|
894 | );
|
895 | this.printOnNewline(
|
896 | swift`return ${structName}(unsafeResultMap: resultMap)`
|
897 | );
|
898 | });
|
899 | this.printOnNewline(swift`set`);
|
900 | this.withinBlock(() => {
|
901 | this.printOnNewline(
|
902 | swift`guard let newValue = newValue else { return }`
|
903 | );
|
904 | this.printOnNewline(swift`resultMap = newValue.resultMap`);
|
905 | });
|
906 | });
|
907 | }
|
908 |
|
909 | initializerDeclarationForProperties(properties: Property[]) {
|
910 | this.printOnNewline(swift`public init`);
|
911 | this.parametersForProperties(properties);
|
912 |
|
913 | this.withinBlock(() => {
|
914 | properties.forEach(({ propertyName }) => {
|
915 | this.printOnNewline(
|
916 | swift`self.${propertyName} = ${this.helpers.internalParameterName(
|
917 | propertyName,
|
918 | properties
|
919 | )}`
|
920 | );
|
921 | });
|
922 | });
|
923 | }
|
924 |
|
925 | parametersForProperties(properties: Property[]) {
|
926 | this.print(swift`(`);
|
927 | this.print(
|
928 | join(
|
929 | properties.map(({ propertyName, typeName, isOptional }) => {
|
930 | const internalName = this.helpers.internalParameterName(
|
931 | propertyName,
|
932 | properties
|
933 | );
|
934 | const decl =
|
935 | internalName === propertyName
|
936 | ? propertyName
|
937 | : swift`${propertyName} ${internalName}`;
|
938 | return join([
|
939 | swift`${decl}: ${typeName}`,
|
940 | isOptional ? swift` = nil` : undefined
|
941 | ]);
|
942 | }),
|
943 | ", "
|
944 | )
|
945 | );
|
946 | this.print(swift`)`);
|
947 | }
|
948 |
|
949 | typeCaseInitialization(typeCase: TypeCase) {
|
950 | if (typeCase.variants.length < 1) {
|
951 | this.selectionSetInitialization(typeCase.default);
|
952 | return;
|
953 | }
|
954 |
|
955 | this.print(swift`[`);
|
956 | this.withIndent(() => {
|
957 | this.printOnNewline(swift`GraphQLTypeCase(`);
|
958 | this.withIndent(() => {
|
959 | this.printOnNewline(swift`variants: [`);
|
960 | this.print(
|
961 | join(
|
962 | typeCase.variants.flatMap(variant => {
|
963 | const structName = this.helpers.structNameForVariant(variant);
|
964 | return variant.possibleTypes.map(
|
965 | type =>
|
966 | swift`${SwiftSource.string(
|
967 | type.toString()
|
968 | )}: ${structName}.selections`
|
969 | );
|
970 | }),
|
971 | ", "
|
972 | )
|
973 | );
|
974 | this.print(swift`],`);
|
975 | this.printOnNewline(swift`default: `);
|
976 | this.selectionSetInitialization(typeCase.default);
|
977 | });
|
978 | this.printOnNewline(swift`)`);
|
979 | });
|
980 | this.printOnNewline(swift`]`);
|
981 | }
|
982 |
|
983 | selectionSetInitialization(selectionSet: SelectionSet) {
|
984 | this.print(swift`[`);
|
985 | this.withIndent(() => {
|
986 | for (const selection of selectionSet.selections) {
|
987 | switch (selection.kind) {
|
988 | case "Field": {
|
989 | const { name, alias, args, type } = selection;
|
990 | const responseKey = selection.alias || selection.name;
|
991 | const structName = this.helpers.structNameForPropertyName(
|
992 | responseKey
|
993 | );
|
994 |
|
995 | this.printOnNewline(swift`GraphQLField(`);
|
996 | this.print(
|
997 | join(
|
998 | [
|
999 | swift`${SwiftSource.string(name)}`,
|
1000 | alias
|
1001 | ? swift`alias: ${SwiftSource.string(alias)}`
|
1002 | : undefined,
|
1003 | args && args.length
|
1004 | ? swift`arguments: ${this.helpers.dictionaryLiteralForFieldArguments(
|
1005 | args
|
1006 | )}`
|
1007 | : undefined,
|
1008 | swift`type: ${this.helpers.fieldTypeEnum(type, structName)}`
|
1009 | ],
|
1010 | ", "
|
1011 | )
|
1012 | );
|
1013 | this.print(swift`),`);
|
1014 | break;
|
1015 | }
|
1016 | case "BooleanCondition":
|
1017 | this.printOnNewline(swift`GraphQLBooleanCondition(`);
|
1018 | this.print(
|
1019 | join(
|
1020 | [
|
1021 | swift`variableName: ${SwiftSource.string(
|
1022 | selection.variableName
|
1023 | )}`,
|
1024 | swift`inverted: ${selection.inverted}`,
|
1025 | swift`selections: `
|
1026 | ],
|
1027 | ", "
|
1028 | )
|
1029 | );
|
1030 | this.selectionSetInitialization(selection.selectionSet);
|
1031 | this.print(swift`),`);
|
1032 | break;
|
1033 | case "TypeCondition": {
|
1034 | this.printOnNewline(swift`GraphQLTypeCondition(`);
|
1035 | this.print(
|
1036 | join(
|
1037 | [
|
1038 | swift`possibleTypes: [${join(
|
1039 | selection.selectionSet.possibleTypes.map(
|
1040 | type => swift`${SwiftSource.string(type.name)}`
|
1041 | ),
|
1042 | ", "
|
1043 | )}]`,
|
1044 | swift`selections: `
|
1045 | ],
|
1046 | ", "
|
1047 | )
|
1048 | );
|
1049 | this.selectionSetInitialization(selection.selectionSet);
|
1050 | this.print(swift`),`);
|
1051 | break;
|
1052 | }
|
1053 | case "FragmentSpread": {
|
1054 | const structName = this.helpers.structNameForFragmentName(
|
1055 | selection.fragmentName
|
1056 | );
|
1057 | this.printOnNewline(
|
1058 | swift`GraphQLFragmentSpread(${structName}.self),`
|
1059 | );
|
1060 | break;
|
1061 | }
|
1062 | }
|
1063 | }
|
1064 | });
|
1065 | this.printOnNewline(swift`]`);
|
1066 | }
|
1067 |
|
1068 | /**
|
1069 | * Generates a type declaration for the given `GraphQLType`
|
1070 | *
|
1071 | * @param type The graphQLType to generate a type declaration for.
|
1072 | * @param outputIndividualFiles If this operation is being output as individual files, to help prevent
|
1073 | * redundant usages of the `public` modifier in enum extensions.
|
1074 | */
|
1075 | typeDeclarationForGraphQLType(
|
1076 | type: GraphQLType,
|
1077 | outputIndividualFiles: boolean
|
1078 | ) {
|
1079 | if (isEnumType(type)) {
|
1080 | this.enumerationDeclaration(type);
|
1081 | } else if (isInputObjectType(type)) {
|
1082 | this.structDeclarationForInputObjectType(type, outputIndividualFiles);
|
1083 | }
|
1084 | }
|
1085 |
|
1086 | enumerationDeclaration(type: GraphQLEnumType) {
|
1087 | const { name, description } = type;
|
1088 | const values = type.getValues().filter(value => {
|
1089 | return (
|
1090 | !value.isDeprecated || !this.context.options.omitDeprecatedEnumCases
|
1091 | );
|
1092 | });
|
1093 |
|
1094 | this.printNewlineIfNeeded();
|
1095 | this.comment(description || undefined);
|
1096 | this.printOnNewline(
|
1097 | swift`public enum ${name}: RawRepresentable, Equatable, Hashable, CaseIterable, Apollo.JSONDecodable, Apollo.JSONEncodable`
|
1098 | );
|
1099 | this.withinBlock(() => {
|
1100 | this.printOnNewline(swift`public typealias RawValue = String`);
|
1101 |
|
1102 | values.forEach(value => {
|
1103 | this.comment(value.description || undefined);
|
1104 | this.deprecationAttributes(
|
1105 | value.isDeprecated,
|
1106 | value.deprecationReason || undefined
|
1107 | );
|
1108 | this.printOnNewline(
|
1109 | swift`case ${this.helpers.enumCaseName(value.name)}`
|
1110 | );
|
1111 | });
|
1112 | this.comment("Auto generated constant for unknown enum values");
|
1113 | this.printOnNewline(swift`case __unknown(RawValue)`);
|
1114 |
|
1115 | this.printNewlineIfNeeded();
|
1116 | this.printOnNewline(swift`public init?(rawValue: RawValue)`);
|
1117 | this.withinBlock(() => {
|
1118 | this.printOnNewline(swift`switch rawValue`);
|
1119 | this.withinBlock(() => {
|
1120 | values.forEach(value => {
|
1121 | this.printOnNewline(
|
1122 | swift`case ${SwiftSource.string(
|
1123 | value.value
|
1124 | )}: self = ${this.helpers.enumDotCaseName(value.name)}`
|
1125 | );
|
1126 | });
|
1127 | this.printOnNewline(swift`default: self = .__unknown(rawValue)`);
|
1128 | });
|
1129 | });
|
1130 |
|
1131 | this.printNewlineIfNeeded();
|
1132 | this.printOnNewline(swift`public var rawValue: RawValue`);
|
1133 | this.withinBlock(() => {
|
1134 | this.printOnNewline(swift`switch self`);
|
1135 | this.withinBlock(() => {
|
1136 | values.forEach(value => {
|
1137 | this.printOnNewline(
|
1138 | swift`case ${this.helpers.enumDotCaseName(
|
1139 | value.name
|
1140 | )}: return ${SwiftSource.string(value.value)}`
|
1141 | );
|
1142 | });
|
1143 | this.printOnNewline(swift`case .__unknown(let value): return value`);
|
1144 | });
|
1145 | });
|
1146 |
|
1147 | this.printNewlineIfNeeded();
|
1148 | this.printOnNewline(
|
1149 | swift`public static func == (lhs: ${name}, rhs: ${name}) -> Bool`
|
1150 | );
|
1151 | this.withinBlock(() => {
|
1152 | this.printOnNewline(swift`switch (lhs, rhs)`);
|
1153 | this.withinBlock(() => {
|
1154 | values.forEach(value => {
|
1155 | const enumDotCaseName = this.helpers.enumDotCaseName(value.name);
|
1156 | const tuple = swift`(${enumDotCaseName}, ${enumDotCaseName})`;
|
1157 | this.printOnNewline(swift`case ${tuple}: return true`);
|
1158 | });
|
1159 | this.printOnNewline(
|
1160 | swift`case (.__unknown(let lhsValue), .__unknown(let rhsValue)): return lhsValue == rhsValue`
|
1161 | );
|
1162 | this.printOnNewline(swift`default: return false`);
|
1163 | });
|
1164 | });
|
1165 |
|
1166 | this.printNewlineIfNeeded();
|
1167 | this.printOnNewline(swift`public static var allCases: [${name}]`);
|
1168 | this.withinBlock(() => {
|
1169 | this.printOnNewline(swift`return [`);
|
1170 | values.forEach(value => {
|
1171 | const enumDotCaseName = this.helpers.enumDotCaseName(value.name);
|
1172 | this.withIndent(() => {
|
1173 | this.printOnNewline(swift`${enumDotCaseName},`);
|
1174 | });
|
1175 | });
|
1176 | this.printOnNewline(swift`]`);
|
1177 | });
|
1178 | });
|
1179 | }
|
1180 |
|
1181 | /**
|
1182 | * Generates a struct for a `GraphQLInputObjectType`.
|
1183 | *
|
1184 | * @param type The input type to generate code for
|
1185 | * @param outputIndividualFiles If this operation is being output as individual files, to help prevent
|
1186 | * redundant usages of the `public` modifier in enum extensions.
|
1187 | */
|
1188 | structDeclarationForInputObjectType(
|
1189 | type: GraphQLInputObjectType,
|
1190 | outputIndividualFiles: boolean
|
1191 | ) {
|
1192 | const { name: structName, description } = type;
|
1193 | const adoptedProtocols = ["GraphQLMapConvertible"];
|
1194 | const fields = Object.values(type.getFields());
|
1195 |
|
1196 | const properties = fields.map(
|
1197 | this.helpers.propertyFromInputField,
|
1198 | this.helpers
|
1199 | );
|
1200 |
|
1201 | properties.forEach(property => {
|
1202 | if (property.isOptional) {
|
1203 | property.typeName = `Swift.Optional<${property.typeName}>`;
|
1204 | }
|
1205 | });
|
1206 |
|
1207 | this.structDeclaration(
|
1208 | { structName, description: description || undefined, adoptedProtocols },
|
1209 | outputIndividualFiles,
|
1210 | () => {
|
1211 | this.printOnNewline(swift`public var graphQLMap: GraphQLMap`);
|
1212 |
|
1213 | this.printNewlineIfNeeded();
|
1214 |
|
1215 | if (properties.length > 0) {
|
1216 | this.comment("- Parameters:");
|
1217 | properties.forEach(property => {
|
1218 | var propertyDescription = "";
|
1219 | if (property.description) {
|
1220 | propertyDescription = `: ${property.description}`;
|
1221 | }
|
1222 | this.comment(
|
1223 | ` - ${property.propertyName}${propertyDescription}`,
|
1224 | false
|
1225 | );
|
1226 | });
|
1227 | }
|
1228 |
|
1229 | this.printOnNewline(swift`public init`);
|
1230 | this.print(swift`(`);
|
1231 | this.print(
|
1232 | join(
|
1233 | properties.map(({ propertyName, typeName, isOptional }) => {
|
1234 | const internalName = this.helpers.internalParameterName(
|
1235 | propertyName,
|
1236 | properties
|
1237 | );
|
1238 | const decl =
|
1239 | internalName === propertyName
|
1240 | ? propertyName
|
1241 | : swift`${propertyName} ${internalName}`;
|
1242 | return join([
|
1243 | swift`${decl}: ${typeName}`,
|
1244 | isOptional ? swift` = nil` : undefined
|
1245 | ]);
|
1246 | }),
|
1247 | ", "
|
1248 | )
|
1249 | );
|
1250 | this.print(swift`)`);
|
1251 |
|
1252 | this.withinBlock(() => {
|
1253 | this.printOnNewline(
|
1254 | wrap(
|
1255 | swift`graphQLMap = [`,
|
1256 | join(
|
1257 | properties.map(
|
1258 | ({ name, propertyName }) =>
|
1259 | swift`${SwiftSource.string(
|
1260 | name
|
1261 | )}: ${this.helpers.internalParameterName(
|
1262 | propertyName,
|
1263 | properties
|
1264 | )}`
|
1265 | ),
|
1266 | ", "
|
1267 | ) || swift`:`,
|
1268 | swift`]`
|
1269 | )
|
1270 | );
|
1271 | });
|
1272 |
|
1273 | for (const {
|
1274 | name,
|
1275 | propertyName,
|
1276 | typeName,
|
1277 | description,
|
1278 | isOptional
|
1279 | } of properties) {
|
1280 | this.printNewlineIfNeeded();
|
1281 | this.comment(description || undefined);
|
1282 | this.printOnNewline(swift`public var ${propertyName}: ${typeName}`);
|
1283 | this.withinBlock(() => {
|
1284 | this.printOnNewline(swift`get`);
|
1285 | this.withinBlock(() => {
|
1286 | if (isOptional) {
|
1287 | this.printOnNewline(
|
1288 | swift`return graphQLMap[${SwiftSource.string(
|
1289 | name
|
1290 | )}] as? ${typeName} ?? ${typeName}.none`
|
1291 | );
|
1292 | } else {
|
1293 | this.printOnNewline(
|
1294 | swift`return graphQLMap[${SwiftSource.string(
|
1295 | name
|
1296 | )}] as! ${typeName}`
|
1297 | );
|
1298 | }
|
1299 | });
|
1300 | this.printOnNewline(swift`set`);
|
1301 | this.withinBlock(() => {
|
1302 | this.printOnNewline(
|
1303 | swift`graphQLMap.updateValue(newValue, forKey: ${SwiftSource.string(
|
1304 | name
|
1305 | )})`
|
1306 | );
|
1307 | });
|
1308 | });
|
1309 | }
|
1310 | }
|
1311 | );
|
1312 | }
|
1313 | }
|
1314 |
|
\ | No newline at end of file |