-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.ts
458 lines (412 loc) · 19.1 KB
/
index.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import { PluginFunction, Types } from "@graphql-codegen/plugin-helpers";
import { convertFactory, ConvertFn, NamingConvention, RawConfig } from "@graphql-codegen/visitor-plugin-common";
import { sentenceCase } from "change-case";
import {
GraphQLEnumType,
GraphQLField,
GraphQLInterfaceType,
GraphQLList,
GraphQLNamedType,
GraphQLNonNull,
GraphQLObjectType,
GraphQLOutputType,
GraphQLScalarType,
GraphQLSchema,
GraphQLUnionType,
} from "graphql";
import { Code, code, imp, Import, joinCode } from "ts-poet";
import PluginOutput = Types.PluginOutput;
/** Generates `newProject({ ... })` factory functions in our `graphql-types` codegen output. */
export const plugin: PluginFunction = async (schema, documents, config: Config) => {
const convert = convertFactory(config);
const chunks: Code[] = [];
// Create a map of interface -> implementing types
const interfaceImpls: Record<string, string[]> = {};
Object.values(schema.getTypeMap()).forEach((type) => {
if (type instanceof GraphQLObjectType) {
for (const i of type.getInterfaces()) {
(interfaceImpls[i.name] ??= []).push(type.name);
}
}
});
chunks.push(code`const factories: Record<string, Function> = {};`);
chunks.push(
code`type RequireTypename<T extends { __typename?: string; }> = Omit<T, "__typename"> & Required<Pick<T, "__typename">>;`,
);
const hasFactories = generateFactoryFunctions(config, convert, schema, interfaceImpls, chunks);
generateInterfaceFactoryFunctions(config, interfaceImpls, chunks);
generateEnumDetailHelperFunctions(config, schema, chunks);
addNextIdMethods(chunks, config);
generateMaybeFunctions(chunks);
if (!hasFactories) {
chunks.push(
code`// No factories found, make sure your node_modules does not have multiple versions of the 'graphql' library`,
);
}
const content = await code`${chunks}`.toString();
return { content } as PluginOutput;
};
function generateFactoryFunctions(
config: Config,
convertFn: ConvertFn,
schema: GraphQLSchema,
interfaceImpls: Record<string, string[]>,
chunks: Code[],
): boolean {
let hasFactories = false;
Object.values(schema.getTypeMap()).forEach((type) => {
if (shouldCreateFactory(type)) {
chunks.push(newFactory(config, convertFn, interfaceImpls, type));
hasFactories = true;
}
});
return hasFactories;
}
function generateInterfaceFactoryFunctions(config: Config, interfaceImpls: Record<string, string[]>, chunks: Code[]) {
Object.entries(interfaceImpls).forEach(([interfaceName, impls]) => {
chunks.push(...newInterfaceFactory(config, interfaceName, impls));
});
}
/** Makes helper methods to convert the "maybe enum / maybe enum detail" factory options into enum details. */
function generateEnumDetailHelperFunctions(config: Config, schema: GraphQLSchema, chunks: Code[]) {
const usedEnumDetailTypes = new Set(
Object.values(schema.getTypeMap())
.filter(shouldCreateFactory)
.flatMap((type) => {
return Object.values(type.getFields())
.map((f) => unwrapNullsAndLists(f.type))
.filter(isEnumDetailObject);
}),
);
usedEnumDetailTypes.forEach((type) => {
const enumType = getRealEnumForEnumDetailObject(type);
const scopedEnumTypeName = maybeImport(config, enumType.name);
const scopedTypeName = maybeImport(config, type.name);
const enumOrDetail = code`${type.name}Options | ${scopedEnumTypeName} | undefined`;
chunks.push(code`
const enumDetailNameOf${enumType.name} = {
${enumType
.getValues()
.map((v) => `${v.value}: "${sentenceCase(v.value)}"`)
.join(", ")}
};
function enumOrDetailOf${enumType.name}(enumOrDetail: ${enumOrDetail}): ${scopedTypeName} {
if (enumOrDetail === undefined) {
return new${type.name}();
} else if (typeof enumOrDetail === "object" && "code" in enumOrDetail) {
return {
__typename: "${type.name}",
code: enumOrDetail.code!,
name: enumDetailNameOf${enumType.name}[enumOrDetail.code!],
...enumOrDetail,
} as ${scopedTypeName}
} else {
return new${type.name}({
code: enumOrDetail as ${scopedEnumTypeName},
name: enumDetailNameOf${enumType.name}[enumOrDetail as ${scopedEnumTypeName}],
});
}
}
function enumOrDetailOrNullOf${enumType.name}(enumOrDetail: ${enumOrDetail} | null): ${scopedTypeName} | null {
if (enumOrDetail === null) {
return null;
}
return enumOrDetailOf${enumType.name}(enumOrDetail);
}
`);
});
}
/** Creates a `new${type}` function for the given `type`. */
function newFactory(
config: Config,
convertFn: ConvertFn,
interfaceImpls: Record<string, string[]>,
type: GraphQLObjectType,
): Code {
const typeImp = maybeImport(config, type.name);
function generateListField(f: GraphQLField<any, any>, fieldType: GraphQLList<any>): string {
// If this is a list of objects, initialize it as normal, but then also probe it to ensure each
// passed-in value goes through `maybeNew` to ensure `__typename` is set, otherwise Apollo breaks.
let elementType = fieldType.ofType as GraphQLOutputType;
if (elementType instanceof GraphQLNonNull) {
elementType = elementType.ofType;
if (isEnumDetailObject(elementType)) {
const enumType = getRealEnumForEnumDetailObject(elementType);
return `o.${f.name} = (options.${f.name} ?? []).map(i => enumOrDetailOf${enumType.name}(i));`;
} else if (elementType instanceof GraphQLObjectType || elementType instanceof GraphQLInterfaceType) {
return `o.${f.name} = (options.${f.name} ?? []).map(i => maybeNew("${elementType.name}", i, cache, options.hasOwnProperty("${f.name}")));`;
} else if (elementType instanceof GraphQLUnionType) {
return `o.${f.name} = (options.${f.name} ?? []).map(i => maybeNew(i?.__typename ?? "{${elementType.getTypes()[0].name}", i, cache, options.hasOwnProperty("${f.name}")));`;
}
} else if (isEnumDetailObject(elementType)) {
const enumType = getRealEnumForEnumDetailObject(elementType);
return `o.${f.name} = (options.${f.name} ?? []).map(i => enumOrDetailOrNullOf${enumType.name}(i));`;
} else if (elementType instanceof GraphQLObjectType || elementType instanceof GraphQLInterfaceType) {
return `o.${f.name} = (options.${f.name} ?? []).map(i => maybeNewOrNull("${elementType.name}", i, cache));`;
} else if (elementType instanceof GraphQLUnionType) {
return `o.${f.name} = (options.${f.name} ?? []).map(i => maybeNewOrNull(i?.__typename ?? "{${elementType.getTypes()[0].name}", i, cache));`;
}
return `o.${f.name} = options.${f.name} ?? [];`;
}
// Instead of using `DeepPartial`, we make an explicit `AuthorOptions` for each type, primarily
// b/c the `AuthorOption.books: [BookOption]` will support enum details recursively.
const optionFields: Code[] = Object.values(type.getFields()).map((f) => {
const fieldType = maybeDenull(f.type);
const orNull = f.type instanceof GraphQLNonNull ? "" : " | null";
if (fieldType instanceof GraphQLObjectType && isEnumDetailObject(fieldType)) {
return code`${f.name}?: ${fieldType.name}Options | ${getRealImportedEnum(config, fieldType)}${orNull};`;
} else if (fieldType instanceof GraphQLObjectType) {
return code`${f.name}?: ${fieldType.name} | ${fieldType.name}Options${orNull};`;
} else if (fieldType instanceof GraphQLInterfaceType) {
return code`${f.name}?: ${interfaceImpls[fieldType.name].join(" | ")} | ${maybeImport(config, fieldType.name)} | ${fieldType.name}Options${orNull};`;
} else if (fieldType instanceof GraphQLUnionType) {
const optionTypes = fieldType
.getTypes()
.map((t) => t.name)
.map((name, i) => (i === 0 ? `${name}Options` : `RequireTypename<${name}Options>`));
return code`${f.name}?: ${maybeImport(config, fieldType.name)} | ${optionTypes.join(" | ")}${orNull};`;
} else if (fieldType instanceof GraphQLList) {
const elementType = maybeDenull(fieldType.ofType) as GraphQLNamedType;
const isNonNull = fieldType.ofType instanceof GraphQLNonNull;
const optionsType = code`${elementType.name}Options`;
const maybeMaybeType = (type: Code) => (isNonNull ? type : code`${maybeImport(config, "Maybe")}<${type}>`);
if (elementType instanceof GraphQLObjectType) {
return code`${f.name}?: Array<${maybeMaybeType(code`${elementType.name} | ${optionsType}`)}>${orNull};`;
} else if (elementType instanceof GraphQLInterfaceType) {
return code`${f.name}?: Array<${maybeMaybeType(code`${interfaceImpls[elementType.name].join(" | ")} | ${maybeImport(config, elementType.name)} | ${optionsType}`)}>${orNull};`;
} else if (elementType instanceof GraphQLUnionType) {
const optionTypes = elementType
.getTypes()
.map((t) => t.name)
.map((name, i) => (i === 0 ? `${name}Options` : `RequireTypename<${name}Options>`));
return code`${f.name}?: Array<${maybeMaybeType(code`${maybeImport(config, elementType.name)} | ${optionTypes.join(" | ")}`)}>${orNull};`;
} else {
return code`${f.name}?: ${typeImp}["${f.name}"]${orNull};`;
}
} else {
return code`${f.name}?: ${typeImp}["${f.name}"];`;
}
});
const factory = code`
export interface ${type.name}Options {
__typename?: '${type.name}';
${joinCode(optionFields, { on: "\n" })}
}
export function new${type.name}(options: ${type.name}Options = {}, cache: Record<string, any> = {}): ${typeImp} {
const o = (options.__typename ? options : cache["${type.name}"] = {}) as ${typeImp};
(cache.all ??= new Set()).add(o);
o.__typename = '${type.name}';
${Object.values(type.getFields()).map((f) => {
if (f.type instanceof GraphQLNonNull) {
const fieldType = f.type.ofType;
if (isEnumDetailObject(fieldType)) {
const enumType = getRealEnumForEnumDetailObject(fieldType);
return `o.${f.name} = enumOrDetailOf${enumType.name}(options.${f.name});`;
} else if (fieldType instanceof GraphQLList) {
return generateListField(f, fieldType);
} else if (fieldType instanceof GraphQLObjectType || fieldType instanceof GraphQLInterfaceType) {
return `o.${f.name} = maybeNew("${fieldType.name}", options.${f.name}, cache, options.hasOwnProperty("${f.name}"));`;
} else if (fieldType instanceof GraphQLUnionType) {
return `o.${f.name} = maybeNew(options.${f.name}?.__typename ?? "${fieldType.getTypes()[0].name}", options.${f.name}, cache);`;
} else {
return code`o.${f.name} = options.${f.name} ?? ${getInitializer(config, convertFn, type, f, fieldType)};`;
}
} else if (isEnumDetailObject(f.type)) {
const enumType = getRealEnumForEnumDetailObject(f.type);
return `o.${f.name} = enumOrDetailOrNullOf${enumType.name}(options.${f.name});`;
} else if (f.type instanceof GraphQLList) {
return generateListField(f, f.type);
} else if (f.type instanceof GraphQLObjectType || f.type instanceof GraphQLInterfaceType) {
return `o.${f.name} = maybeNewOrNull("${(f.type as any).name}", options.${f.name}, cache);`;
} else if (f.type instanceof GraphQLUnionType) {
return `o.${f.name} = maybeNewOrNull(options.${f.name}?.__typename ?? "${f.type.getTypes()[0].name}", options.${f.name}, cache);`;
} else {
return `o.${f.name} = options.${f.name} ?? null;`;
}
})}
return o;
}
factories["${type.name}"] = new${type.name};
`;
return factory;
}
function generateMaybeFunctions(chunks: Code[]): void {
const maybeFunctions = code`
function maybeNew(type: string, value: { __typename?: string } | object | undefined, cache: Record<string, any>, isSet: boolean = false): any {
if (value === undefined) {
return isSet ? undefined : cache[type] || factories[type]({}, cache)
} else if ("__typename" in value && value.__typename) {
return cache.all?.has(value) ? value : factories[value.__typename](value, cache);
} else {
return factories[type](value, cache);
}
}
function maybeNewOrNull(type: string, value: { __typename?: string } | object | undefined | null, cache: Record<string, any>): any {
if (!value) {
return null;
} else if ("__typename" in value && value.__typename) {
return cache.all?.has(value) ? value : factories[value.__typename](value, cache);
} else {
return factories[type](value, cache);
}
}`;
chunks.push(maybeFunctions);
}
/** Creates a `new${type}` function for the given `type`. */
function newInterfaceFactory(config: Config, interfaceName: string, impls: string[]): Code[] {
const defaultImpl = impls[0] || fail(`Interface ${interfaceName} is unused`);
return [
code`
export type ${interfaceName}Options = ${impls.map((name, i) => (i === 0 ? `${name}Options` : `RequireTypename<${name}Options>`)).join(" | ")};
`,
code`
export type ${interfaceName}Type = ${joinCode(
impls.map((type) => maybeImport(config, type)),
{ on: " | " },
)};
`,
code`
export type ${interfaceName}TypeName = ${impls.map((n) => `"${n}"`).join(" | ")};
`,
code`
export function new${interfaceName}(): ${defaultImpl};
${impls.map((name, i) => code`export function new${interfaceName}(options: ${i === 0 ? `${name}Options` : `RequireTypename<${name}Options>`}, cache?: Record<string, any>): ${name};`)}
export function new${interfaceName}(options: ${interfaceName}Options = {}, cache: Record<string, any> = {}): ${interfaceName}Type {
const { __typename = "${defaultImpl}" } = options ?? {};
const maybeCached = Object.keys(options).length === 0 ? cache[__typename] : undefined
return maybeCached ?? maybeNew(__typename, options ?? {}, cache);
}
`,
code`
factories["${interfaceName}"] = new${interfaceName};
`,
];
}
/** Returns a default value for the given field's type, i.e. strings are "", ints are 0, arrays are []. */
function getInitializer(
config: Config,
convertFn: ConvertFn,
object: GraphQLObjectType,
field: GraphQLField<any, any, any>,
type: GraphQLOutputType,
): string | Code {
if (type instanceof GraphQLList) {
// We could potentially make a dummy entry in every list, but would we risk infinite loops between parents/children?
return `[]`;
} else if (type instanceof GraphQLEnumType) {
const defaultEnumValue = type.getValues()[0];
// The default behavior of graphql-codegen is that enums do drop underscores, but
// type names don't; emulate that by passing `transformUnderscore` here. If the user
// _does_ have it overridden in their config, then that causes enums & types to be
// treated exactly the same.
//
// Todo: we should also check `ignoreEnumValuesFromSchema` and `enumValues` in the config:
// https://github.com/dotansimha/graphql-code-generator/blob/master/packages/plugins/other/visitor-plugin-common/src/base-types-visitor.ts#L921
const name = convertFn(defaultEnumValue.astNode || defaultEnumValue.value, { transformUnderscore: true });
return code`${maybeImport(config, type.name)}.${name}`;
} else if (type instanceof GraphQLScalarType) {
if (type.name === "Int") {
return `0`;
} else if (type.name === "Boolean") {
return `false`;
} else if (field.name === "id" && type.name === "ID") {
// Only call for the `id` field, since we don't want to generate new IDs if the object contains other ID fields
return `nextFactoryId("${object.name}")`;
} else if (type.name === "String" || type.name === "ID") {
// Treat String and ID fields the same, as long as it is not the `id: ID` field
const maybeCode = isEnumDetailObject(object) && object.getFields()["code"];
if (maybeCode) {
const value = getRealEnumForEnumDetailObject(object).getValues()[0].value;
return `"${sentenceCase(value)}"`;
} else {
return `"${field.name}"`;
}
}
const defaultFromConfig = config.scalarDefaults?.[type.name];
if (defaultFromConfig) {
return code`${toImp(defaultFromConfig)}()`;
}
return `"" as any`;
}
return `undefined as any`;
}
/** Look for the FooDetail/code/name pattern of our enum detail objects. */
function isEnumDetailObject(object: GraphQLOutputType): object is GraphQLObjectType {
return (
object instanceof GraphQLObjectType &&
object.name.endsWith("Detail") &&
Object.keys(object.getFields()).length >= 2 &&
!!object.getFields()["code"] &&
!!object.getFields()["name"]
);
}
function getRealEnumForEnumDetailObject(detailObject: GraphQLOutputType): GraphQLEnumType {
return unwrapNotNull((unwrapNotNull(detailObject) as GraphQLObjectType).getFields()["code"]!.type) as GraphQLEnumType;
}
function getRealImportedEnum(config: Config, detailObject: GraphQLOutputType): Code {
return maybeImport(config, getRealEnumForEnumDetailObject(detailObject).name);
}
function unwrapNotNull(type: GraphQLOutputType): GraphQLOutputType {
if (type instanceof GraphQLNonNull) {
return type.ofType;
} else {
return type;
}
}
/** Unwrap `Foo!` -> `Foo` and `[Foo!]!` -> `Foo`. */
function unwrapNullsAndLists(type: GraphQLOutputType): GraphQLOutputType {
if (type instanceof GraphQLNonNull) {
type = type.ofType;
}
if (type instanceof GraphQLList) {
type = type.ofType;
}
if (type instanceof GraphQLNonNull) {
type = type.ofType;
}
return type;
}
function shouldCreateFactory(type: GraphQLNamedType): type is GraphQLObjectType {
return (
type instanceof GraphQLObjectType &&
!type.name.startsWith("__") &&
type.name !== "Mutation" &&
type.name !== "Query"
);
}
function addNextIdMethods(chunks: Code[], config: Config): void {
chunks.push(code`
const taggedIds: Record<string, string> = ${config.taggedIds || "{}"};
let nextFactoryIds: Record<string, number> = {};
export function resetFactoryIds() {
nextFactoryIds = {};
}
function nextFactoryId(objectName: string): string {
const nextId = nextFactoryIds[objectName] || 1;
nextFactoryIds[objectName] = nextId + 1;
const tag = taggedIds[objectName] ?? objectName.replace(/[a-z]/g, "").toLowerCase();
return tag + ":" + nextId;
}
`);
}
function maybeImport(config: Config, typeName: string): Code {
return code`${!!config.typesFilePath ? imp(`${typeName}@${config.typesFilePath}`) : typeName}`;
}
function maybeDenull(o: GraphQLOutputType): GraphQLOutputType {
return o instanceof GraphQLNonNull ? o.ofType : o;
}
/** The config values we read from the graphql-codegen.yml file. */
export type Config = RawConfig & {
scalarDefaults?: Record<string, string>;
taggedIds?: Record<string, string>;
typesFilePath?: string;
namingConvention?: NamingConvention;
};
// Maps the graphql-code-generation convention of `@src/context#Context` to ts-poet's `Context@@src/context`.
export function toImp(spec: string): Import {
const [path, symbol] = spec.split("#");
return imp(`${symbol}@${path}`);
}
export function fail(message?: string): never {
throw new Error(message || "Failed");
}