-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathbuildObjectType.ts
570 lines (505 loc) · 17.4 KB
/
buildObjectType.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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable no-await-in-loop */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-use-before-define */
import { GraphQLJSON } from 'graphql-type-json';
import {
GraphQLBoolean, GraphQLEnumType,
GraphQLFieldConfig,
GraphQLFloat,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLString,
GraphQLType,
GraphQLUnionType,
} from 'graphql';
import { DateTimeResolver, EmailAddressResolver } from 'graphql-scalars';
import {
Field,
RadioField,
RelationshipField,
SelectField,
UploadField,
ArrayField,
GroupField,
RichTextField,
NumberField,
TextField,
EmailField,
TextareaField,
CodeField,
JSONField,
DateField,
PointField,
CheckboxField,
BlockField,
RowField,
CollapsibleField,
TabsField,
tabHasName,
} from '../../fields/config/types';
import formatName from '../utilities/formatName';
import combineParentName from '../utilities/combineParentName';
import withNullableType from './withNullableType';
import { toWords } from '../../utilities/formatLabels';
import createRichTextRelationshipPromise from '../../fields/richText/richTextRelationshipPromise';
import formatOptions from '../utilities/formatOptions';
import { Payload } from '../../payload';
import buildWhereInputType from './buildWhereInputType';
import isFieldNullable from './isFieldNullable';
type LocaleInputType = {
locale: {
type: GraphQLType;
},
fallbackLocale: {
type: GraphQLType;
},
where: {
type: GraphQLType;
}
}
export type ObjectTypeConfig = {
[path: string]: GraphQLFieldConfig<any, any>
}
type Args = {
payload: Payload
name: string
parentName: string
fields: Field[]
baseFields?: ObjectTypeConfig
forceNullable?: boolean
}
function buildObjectType({
payload,
name,
fields,
parentName,
baseFields = {},
forceNullable,
}: Args): GraphQLObjectType {
const fieldToSchemaMap = {
number: (objectTypeConfig: ObjectTypeConfig, field: NumberField) => {
const type = field?.name === 'id' ? GraphQLInt : GraphQLFloat;
return ({
...objectTypeConfig,
[field.name]: { type: withNullableType(field, field?.hasMany === true ? new GraphQLList(type) : type, forceNullable) },
});
},
text: (objectTypeConfig: ObjectTypeConfig, field: TextField) => ({
...objectTypeConfig,
[field.name]: { type: withNullableType(field, GraphQLString, forceNullable) },
}),
email: (objectTypeConfig: ObjectTypeConfig, field: EmailField) => ({
...objectTypeConfig,
[field.name]: { type: withNullableType(field, EmailAddressResolver, forceNullable) },
}),
textarea: (objectTypeConfig: ObjectTypeConfig, field: TextareaField) => ({
...objectTypeConfig,
[field.name]: { type: withNullableType(field, GraphQLString, forceNullable) },
}),
code: (objectTypeConfig: ObjectTypeConfig, field: CodeField) => ({
...objectTypeConfig,
[field.name]: { type: withNullableType(field, GraphQLString, forceNullable) },
}),
json: (objectTypeConfig: ObjectTypeConfig, field: JSONField) => ({
...objectTypeConfig,
[field.name]: { type: withNullableType(field, GraphQLJSON, forceNullable) },
}),
date: (objectTypeConfig: ObjectTypeConfig, field: DateField) => ({
...objectTypeConfig,
[field.name]: { type: withNullableType(field, DateTimeResolver, forceNullable) },
}),
point: (objectTypeConfig: ObjectTypeConfig, field: PointField) => ({
...objectTypeConfig,
[field.name]: { type: withNullableType(field, new GraphQLList(new GraphQLNonNull(GraphQLFloat)), forceNullable) },
}),
richText: (objectTypeConfig: ObjectTypeConfig, field: RichTextField) => ({
...objectTypeConfig,
[field.name]: {
type: withNullableType(field, GraphQLJSON, forceNullable),
async resolve(parent, args, context) {
let depth = payload.config.defaultDepth;
if (typeof args.depth !== 'undefined') depth = args.depth;
if (depth > 0) {
await createRichTextRelationshipPromise({
req: context.req,
siblingDoc: parent,
depth,
field,
showHiddenFields: false,
});
}
return parent[field.name];
},
args: {
depth: {
type: GraphQLInt,
},
},
},
}),
upload: (objectTypeConfig: ObjectTypeConfig, field: UploadField) => {
const { relationTo } = field;
const uploadName = combineParentName(parentName, toWords(field.name, true));
// If the relationshipType is undefined at this point,
// it can be assumed that this blockType can have a relationship
// to itself. Therefore, we set the relationshipType equal to the blockType
// that is currently being created.
const type = withNullableType(
field,
payload.collections[relationTo].graphQL.type || newlyCreatedBlockType,
forceNullable,
);
const uploadArgs = {} as LocaleInputType;
if (payload.config.localization) {
uploadArgs.locale = {
type: payload.types.localeInputType,
};
uploadArgs.fallbackLocale = {
type: payload.types.fallbackLocaleInputType,
};
}
const relatedCollectionSlug = field.relationTo;
const upload = {
args: uploadArgs,
type,
extensions: { complexity: 20 },
async resolve(parent, args, context) {
const value = parent[field.name];
const locale = args.locale || context.req.locale;
const fallbackLocale = args.fallbackLocale || context.req.fallbackLocale;
const id = value;
if (id) {
const relatedDocument = await context.req.payloadDataLoader.load(JSON.stringify([
relatedCollectionSlug,
id,
0,
0,
locale,
fallbackLocale,
false,
false,
]));
return relatedDocument || null;
}
return null;
},
};
const whereFields = payload.collections[relationTo].config.fields;
upload.args.where = {
type: buildWhereInputType(
uploadName,
whereFields,
uploadName,
),
};
return {
...objectTypeConfig,
[field.name]: upload,
};
},
radio: (objectTypeConfig: ObjectTypeConfig, field: RadioField) => ({
...objectTypeConfig,
[field.name]: {
type: withNullableType(
field,
new GraphQLEnumType({
name: combineParentName(parentName, field.name),
values: formatOptions(field),
}),
forceNullable,
),
},
}),
checkbox: (objectTypeConfig: ObjectTypeConfig, field: CheckboxField) => ({
...objectTypeConfig,
[field.name]: { type: withNullableType(field, GraphQLBoolean, forceNullable) },
}),
select: (objectTypeConfig: ObjectTypeConfig, field: SelectField) => {
const fullName = combineParentName(parentName, field.name);
let type: GraphQLType = new GraphQLEnumType({
name: fullName,
values: formatOptions(field),
});
type = field.hasMany ? new GraphQLList(new GraphQLNonNull(type)) : type;
type = withNullableType(field, type, forceNullable);
return {
...objectTypeConfig,
[field.name]: { type },
};
},
relationship: (objectTypeConfig: ObjectTypeConfig, field: RelationshipField) => {
const { relationTo } = field;
const isRelatedToManyCollections = Array.isArray(relationTo);
const hasManyValues = field.hasMany;
const relationshipName = combineParentName(parentName, toWords(field.name, true));
let type;
let relationToType = null;
if (Array.isArray(relationTo)) {
relationToType = new GraphQLEnumType({
name: `${relationshipName}_RelationTo`,
values: relationTo.reduce((relations, relation) => ({
...relations,
[formatName(relation)]: {
value: relation,
},
}), {}),
});
const types = relationTo.map((relation) => payload.collections[relation].graphQL.type);
type = new GraphQLObjectType({
name: `${relationshipName}_Relationship`,
fields: {
relationTo: {
type: relationToType,
},
value: {
type: new GraphQLUnionType({
name: relationshipName,
types,
async resolveType(data, { req }) {
return payload.collections[data.collection].graphQL.type.name;
},
}),
},
},
});
} else {
({ type } = payload.collections[relationTo as string].graphQL);
}
// If the relationshipType is undefined at this point,
// it can be assumed that this blockType can have a relationship
// to itself. Therefore, we set the relationshipType equal to the blockType
// that is currently being created.
type = type || newlyCreatedBlockType;
const relationshipArgs: {
locale?: unknown
fallbackLocale?: unknown
where?: unknown
page?: unknown
limit?: unknown
} = {};
if (payload.config.localization) {
relationshipArgs.locale = {
type: payload.types.localeInputType,
};
relationshipArgs.fallbackLocale = {
type: payload.types.fallbackLocaleInputType,
};
}
const relationship = {
args: relationshipArgs,
type: withNullableType(
field,
hasManyValues ? new GraphQLList(new GraphQLNonNull(type)) : type,
forceNullable,
),
extensions: { complexity: 10 },
async resolve(parent, args, context) {
const value = parent[field.name];
const locale = args.locale || context.req.locale;
const fallbackLocale = args.fallbackLocale || context.req.fallbackLocale;
let relatedCollectionSlug = field.relationTo;
if (hasManyValues) {
const results = [];
const resultPromises = [];
const createPopulationPromise = async (relatedDoc, i) => {
let id = relatedDoc;
let collectionSlug = field.relationTo;
if (isRelatedToManyCollections) {
collectionSlug = relatedDoc.relationTo;
id = relatedDoc.value;
}
const result = await context.req.payloadDataLoader.load(JSON.stringify([
collectionSlug,
id,
0,
0,
locale,
fallbackLocale,
false,
false,
]));
if (result) {
if (isRelatedToManyCollections) {
results[i] = {
relationTo: collectionSlug,
value: {
...result,
collection: collectionSlug,
},
};
} else {
results[i] = result;
}
}
};
if (value) {
value.forEach((relatedDoc, i) => {
resultPromises.push(createPopulationPromise(relatedDoc, i));
});
}
await Promise.all(resultPromises);
return results;
}
let id = value;
if (isRelatedToManyCollections && value) {
id = value.value;
relatedCollectionSlug = value.relationTo;
}
if (id) {
const relatedDocument = await context.req.payloadDataLoader.load(JSON.stringify([
relatedCollectionSlug,
id,
0,
0,
locale,
fallbackLocale,
false,
false,
]));
if (relatedDocument) {
if (isRelatedToManyCollections) {
return {
relationTo: relatedCollectionSlug,
value: {
...relatedDocument,
collection: relatedCollectionSlug,
},
};
}
return relatedDocument;
}
return null;
}
return null;
},
};
return {
...objectTypeConfig,
[field.name]: relationship,
};
},
array: (objectTypeConfig: ObjectTypeConfig, field: ArrayField) => {
const interfaceName = field?.interfaceName || combineParentName(parentName, toWords(field.name, true));
if (!payload.types.arrayTypes[interfaceName]) {
// eslint-disable-next-line no-param-reassign
payload.types.arrayTypes[interfaceName] = buildObjectType({
payload,
name: interfaceName,
parentName: interfaceName,
fields: field.fields,
forceNullable: isFieldNullable(field, forceNullable),
});
}
const arrayType = new GraphQLList(new GraphQLNonNull(payload.types.arrayTypes[interfaceName]));
return {
...objectTypeConfig,
[field.name]: { type: withNullableType(field, arrayType) },
};
},
group: (objectTypeConfig: ObjectTypeConfig, field: GroupField) => {
const interfaceName = field?.interfaceName || combineParentName(parentName, toWords(field.name, true));
if (!payload.types.groupTypes[interfaceName]) {
// eslint-disable-next-line no-param-reassign
payload.types.groupTypes[interfaceName] = buildObjectType({
payload,
name: interfaceName,
parentName: interfaceName,
fields: field.fields,
forceNullable: isFieldNullable(field, forceNullable),
});
}
return {
...objectTypeConfig,
[field.name]: { type: payload.types.groupTypes[interfaceName] },
};
},
blocks: (objectTypeConfig: ObjectTypeConfig, field: BlockField) => {
const blockTypes = field.blocks.map((block) => {
if (!payload.types.blockTypes[block.slug]) {
const interfaceName = block?.interfaceName || block?.graphQL?.singularName || toWords(block.slug, true);
// eslint-disable-next-line no-param-reassign
payload.types.blockTypes[block.slug] = buildObjectType({
payload,
name: interfaceName,
parentName: interfaceName,
fields: [
...block.fields,
{
name: 'blockType',
type: 'text',
},
],
forceNullable,
});
}
return payload.types.blockTypes[block.slug];
});
const fullName = combineParentName(parentName, toWords(field.name, true));
const type = new GraphQLList(new GraphQLNonNull(new GraphQLUnionType({
name: fullName,
types: blockTypes,
resolveType: (data) => payload.types.blockTypes[data.blockType].name,
})));
return {
...objectTypeConfig,
[field.name]: { type: withNullableType(field, type) },
};
},
row: (objectTypeConfig: ObjectTypeConfig, field: RowField) => field.fields.reduce((objectTypeConfigWithRowFields, subField) => {
const addSubField = fieldToSchemaMap[subField.type];
if (addSubField) return addSubField(objectTypeConfigWithRowFields, subField);
return objectTypeConfigWithRowFields;
}, objectTypeConfig),
collapsible: (objectTypeConfig: ObjectTypeConfig, field: CollapsibleField) => field.fields.reduce((objectTypeConfigWithCollapsibleFields, subField) => {
const addSubField = fieldToSchemaMap[subField.type];
if (addSubField) return addSubField(objectTypeConfigWithCollapsibleFields, subField);
return objectTypeConfigWithCollapsibleFields;
}, objectTypeConfig),
tabs: (objectTypeConfig: ObjectTypeConfig, field: TabsField) => field.tabs.reduce((tabSchema, tab) => {
if (tabHasName(tab)) {
const interfaceName = tab?.interfaceName || combineParentName(parentName, toWords(tab.name, true));
if (!payload.types.tabTypes[interfaceName]) {
// eslint-disable-next-line no-param-reassign
payload.types.tabTypes[interfaceName] = buildObjectType({
payload,
name: interfaceName,
parentName: interfaceName,
fields: tab.fields,
forceNullable,
});
}
return {
...tabSchema,
[tab.name]: { type: payload.types.tabTypes[interfaceName] },
};
}
return {
...tabSchema,
...tab.fields.reduce((subFieldSchema, subField) => {
const addSubField = fieldToSchemaMap[subField.type];
if (addSubField) return addSubField(subFieldSchema, subField);
return subFieldSchema;
}, tabSchema),
};
}, objectTypeConfig),
};
const objectSchema = {
name,
fields: () => fields.reduce((objectTypeConfig, field) => {
const fieldSchema = fieldToSchemaMap[field.type];
if (typeof fieldSchema !== 'function') {
return objectTypeConfig;
}
return {
...objectTypeConfig,
...fieldSchema(objectTypeConfig, field),
};
}, baseFields),
};
const newlyCreatedBlockType = new GraphQLObjectType(objectSchema);
return newlyCreatedBlockType;
}
export default buildObjectType;