-
-
Notifications
You must be signed in to change notification settings - Fork 797
/
merge-typedefs.ts
269 lines (250 loc) · 7.65 KB
/
merge-typedefs.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import {
DefinitionNode,
DirectiveDefinitionNode,
DocumentNode,
isDefinitionNode,
isSchema,
Kind,
OperationTypeDefinitionNode,
OperationTypeNode,
parse,
ParseOptions,
} from 'graphql';
import {
getDocumentNodeFromSchema,
GetDocumentNodeFromSchemaOptions,
isDocumentNode,
printWithComments,
resetComments,
TypeSource,
} from '@graphql-tools/utils';
import { OnFieldTypeConflict } from './fields.js';
import { mergeGraphQLNodes, schemaDefSymbol } from './merge-nodes.js';
import { DEFAULT_OPERATION_TYPE_NAME_MAP } from './schema-def.js';
import { CompareFn, defaultStringComparator, isSourceTypes, isStringTypes } from './utils.js';
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
export interface Config extends ParseOptions, GetDocumentNodeFromSchemaOptions {
/**
* Produces `schema { query: ..., mutation: ..., subscription: ... }`
*
* Default: true
*/
useSchemaDefinition?: boolean;
/**
* Creates schema definition, even when no types are available
* Produces: `schema { query: Query }`
*
* Default: false
*/
forceSchemaDefinition?: boolean;
/**
* Throws an error on a merge conflict
*
* Default: false
*/
throwOnConflict?: boolean;
/**
* Descriptions are defined as preceding string literals, however an older
* experimental version of the SDL supported preceding comments as
* descriptions. Set to true to enable this deprecated behavior.
* This option is provided to ease adoption and will be removed in v16.
*
* Default: false
*/
commentDescriptions?: boolean;
/**
* Puts the next directive first.
*
* Default: false
*
* @example:
* Given:
* ```graphql
* type User { a: String @foo }
* type User { a: String @bar }
* ```
*
* Results:
* ```
* type User { a: @bar @foo }
* ```
*/
reverseDirectives?: boolean;
exclusions?: string[];
sort?: boolean | CompareFn<string>;
convertExtensions?: boolean;
consistentEnumMerge?: boolean;
ignoreFieldConflicts?: boolean;
/**
* Called if types of the same fields are different
*
* Default: false
*
* @example:
* Given:
* ```graphql
* type User { a: String }
* type User { a: Int }
* ```
*
* Instead of throwing `already defined with a different type` error,
* `onFieldTypeConflict` function is called.
*/
onFieldTypeConflict?: OnFieldTypeConflict;
reverseArguments?: boolean;
}
/**
* Merges multiple type definitions into a single `DocumentNode`
* @param types The type definitions to be merged
*/
export function mergeTypeDefs(typeSource: TypeSource): DocumentNode;
export function mergeTypeDefs(
typeSource: TypeSource,
config?: Partial<Config> & { commentDescriptions: true },
): string;
export function mergeTypeDefs(
typeSource: TypeSource,
config?: Omit<Partial<Config>, 'commentDescriptions'>,
): DocumentNode;
export function mergeTypeDefs(
typeSource: TypeSource,
config?: Partial<Config>,
): DocumentNode | string {
resetComments();
const doc: DocumentNode = {
kind: Kind.DOCUMENT,
definitions: mergeGraphQLTypes(typeSource, {
useSchemaDefinition: true,
forceSchemaDefinition: false,
throwOnConflict: false,
commentDescriptions: false,
...config,
}),
};
let result: any;
if (config?.commentDescriptions) {
result = printWithComments(doc);
} else {
result = doc;
}
resetComments();
return result;
}
function visitTypeSources(
typeSource: TypeSource,
options: ParseOptions & GetDocumentNodeFromSchemaOptions,
allDirectives: DirectiveDefinitionNode[] = [],
allNodes: DefinitionNode[] = [],
visitedTypeSources = new Set<TypeSource>(),
) {
if (typeSource && !visitedTypeSources.has(typeSource)) {
visitedTypeSources.add(typeSource);
if (typeof typeSource === 'function') {
visitTypeSources(typeSource(), options, allDirectives, allNodes, visitedTypeSources);
} else if (Array.isArray(typeSource)) {
for (const type of typeSource) {
visitTypeSources(type, options, allDirectives, allNodes, visitedTypeSources);
}
} else if (isSchema(typeSource)) {
const documentNode = getDocumentNodeFromSchema(typeSource, options);
visitTypeSources(
documentNode.definitions as DefinitionNode[],
options,
allDirectives,
allNodes,
visitedTypeSources,
);
} else if (isStringTypes(typeSource) || isSourceTypes(typeSource)) {
const documentNode = parse(typeSource, options);
visitTypeSources(
documentNode.definitions as DefinitionNode[],
options,
allDirectives,
allNodes,
visitedTypeSources,
);
} else if (typeof typeSource === 'object' && isDefinitionNode(typeSource)) {
if (typeSource.kind === Kind.DIRECTIVE_DEFINITION) {
allDirectives.push(typeSource);
} else {
allNodes.push(typeSource);
}
} else if (isDocumentNode(typeSource)) {
visitTypeSources(
typeSource.definitions as DefinitionNode[],
options,
allDirectives,
allNodes,
visitedTypeSources,
);
} else {
throw new Error(
`typeDefs must contain only strings, documents, schemas, or functions, got ${typeof typeSource}`,
);
}
}
return { allDirectives, allNodes };
}
export function mergeGraphQLTypes(typeSource: TypeSource, config: Config): DefinitionNode[] {
resetComments();
const { allDirectives, allNodes } = visitTypeSources(typeSource, config);
const mergedDirectives = mergeGraphQLNodes(allDirectives, config) as Record<
string,
DirectiveDefinitionNode
>;
const mergedNodes = mergeGraphQLNodes(allNodes, config, mergedDirectives);
if (config?.useSchemaDefinition) {
// XXX: right now we don't handle multiple schema definitions
const schemaDef = mergedNodes[schemaDefSymbol] || {
kind: Kind.SCHEMA_DEFINITION,
operationTypes: [],
};
const operationTypes = schemaDef.operationTypes as OperationTypeDefinitionNode[];
for (const opTypeDefNodeType in DEFAULT_OPERATION_TYPE_NAME_MAP) {
const opTypeDefNode = operationTypes.find(
operationType => operationType.operation === opTypeDefNodeType,
);
if (!opTypeDefNode) {
const possibleRootTypeName = DEFAULT_OPERATION_TYPE_NAME_MAP[opTypeDefNodeType];
const existingPossibleRootType = mergedNodes[possibleRootTypeName];
if (existingPossibleRootType != null && existingPossibleRootType.name != null) {
operationTypes.push({
kind: Kind.OPERATION_TYPE_DEFINITION,
type: {
kind: Kind.NAMED_TYPE,
name: existingPossibleRootType.name,
},
operation: opTypeDefNodeType as OperationTypeNode,
});
}
}
}
if (schemaDef?.operationTypes?.length != null && schemaDef.operationTypes.length > 0) {
mergedNodes[schemaDefSymbol] = schemaDef;
}
}
if (config?.forceSchemaDefinition && !mergedNodes[schemaDefSymbol]?.operationTypes?.length) {
mergedNodes[schemaDefSymbol] = {
kind: Kind.SCHEMA_DEFINITION,
operationTypes: [
{
kind: Kind.OPERATION_TYPE_DEFINITION,
operation: 'query' as OperationTypeNode,
type: {
kind: Kind.NAMED_TYPE,
name: {
kind: Kind.NAME,
value: 'Query',
},
},
},
],
};
}
const mergedNodeDefinitions = Object.values(mergedNodes);
if (config?.sort) {
const sortFn = typeof config.sort === 'function' ? config.sort : defaultStringComparator;
mergedNodeDefinitions.sort((a: any, b: any) => sortFn(a.name?.value, b.name?.value));
}
return mergedNodeDefinitions;
}