1 | import { DocumentNode, FragmentDefinitionNode } from 'graphql';
|
2 | import { invariant, InvariantError } from 'ts-invariant';
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | export function getFragmentQueryDocument(
|
27 | document: DocumentNode,
|
28 | fragmentName?: string,
|
29 | ): DocumentNode {
|
30 | let actualFragmentName = fragmentName;
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | const fragments: Array<FragmentDefinitionNode> = [];
|
36 | document.definitions.forEach(definition => {
|
37 |
|
38 |
|
39 | if (definition.kind === 'OperationDefinition') {
|
40 | throw new InvariantError(
|
41 | `Found a ${definition.operation} operation${
|
42 | definition.name ? ` named '${definition.name.value}'` : ''
|
43 | }. ` +
|
44 | 'No operations are allowed when using a fragment as a query. Only fragments are allowed.',
|
45 | );
|
46 | }
|
47 | // Add our definition to the fragments array if it is a fragment
|
48 | // definition.
|
49 | if (definition.kind === 'FragmentDefinition') {
|
50 | fragments.push(definition);
|
51 | }
|
52 | });
|
53 |
|
54 | // If the user did not give us a fragment name then let us try to get a
|
55 | // name from a single fragment in the definition.
|
56 | if (typeof actualFragmentName === 'undefined') {
|
57 | invariant(
|
58 | fragments.length === 1,
|
59 | `Found ${
|
60 | fragments.length
|
61 | } fragments. \`fragmentName\` must be provided when there is not exactly 1 fragment.`,
|
62 | );
|
63 | actualFragmentName = fragments[0].name.value;
|
64 | }
|
65 |
|
66 |
|
67 |
|
68 | const query: DocumentNode = {
|
69 | ...document,
|
70 | definitions: [
|
71 | {
|
72 | kind: 'OperationDefinition',
|
73 | operation: 'query',
|
74 | selectionSet: {
|
75 | kind: 'SelectionSet',
|
76 | selections: [
|
77 | {
|
78 | kind: 'FragmentSpread',
|
79 | name: {
|
80 | kind: 'Name',
|
81 | value: actualFragmentName,
|
82 | },
|
83 | },
|
84 | ],
|
85 | },
|
86 | },
|
87 | ...document.definitions,
|
88 | ],
|
89 | };
|
90 |
|
91 | return query;
|
92 | }
|