@omnigraph/json-schema 1.0.0-alpha-3fc47d119.0 → 1.0.0-alpha-20230420181317-a95037648

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +5 -4
  2. package/cjs/addExecutionLogicToComposer.js +208 -0
  3. package/cjs/addRootFieldResolver.js +395 -0
  4. package/cjs/bundle.js +65 -0
  5. package/cjs/directives.js +580 -0
  6. package/cjs/getComposerFromJSONSchema.js +1297 -0
  7. package/cjs/getDereferencedJSONSchemaFromOperations.js +33 -0
  8. package/cjs/getGraphQLSchemaFromDereferencedJSONSchema.js +39 -0
  9. package/cjs/getJSONSchemaStringFormatScalarMap.js +61 -0
  10. package/cjs/getReferencedJSONSchemaFromOperations.js +260 -0
  11. package/cjs/getTypeResolverFromOutputTCs.js +69 -0
  12. package/cjs/getUnionTypeComposers.js +85 -0
  13. package/cjs/getValidTypeName.js +20 -0
  14. package/cjs/index.js +14 -0
  15. package/cjs/loadGraphQLSchemaFromJSONSchemas.js +59 -0
  16. package/cjs/package.json +1 -0
  17. package/cjs/resolveDataByUnionInputType.js +40 -0
  18. package/cjs/scalars.js +30 -0
  19. package/cjs/types.js +0 -0
  20. package/cjs/utils.js +65 -0
  21. package/esm/addExecutionLogicToComposer.js +204 -0
  22. package/esm/addRootFieldResolver.js +390 -0
  23. package/esm/bundle.js +60 -0
  24. package/esm/directives.js +565 -0
  25. package/esm/getComposerFromJSONSchema.js +1293 -0
  26. package/esm/getDereferencedJSONSchemaFromOperations.js +29 -0
  27. package/esm/getGraphQLSchemaFromDereferencedJSONSchema.js +35 -0
  28. package/esm/getJSONSchemaStringFormatScalarMap.js +56 -0
  29. package/esm/getReferencedJSONSchemaFromOperations.js +255 -0
  30. package/esm/getTypeResolverFromOutputTCs.js +65 -0
  31. package/esm/getUnionTypeComposers.js +80 -0
  32. package/esm/getValidTypeName.js +16 -0
  33. package/esm/index.js +9 -0
  34. package/esm/loadGraphQLSchemaFromJSONSchemas.js +54 -0
  35. package/esm/resolveDataByUnionInputType.js +36 -0
  36. package/esm/scalars.js +27 -0
  37. package/esm/types.js +0 -0
  38. package/esm/utils.js +57 -0
  39. package/package.json +34 -27
  40. package/typings/addExecutionLogicToComposer.d.cts +14 -0
  41. package/typings/addExecutionLogicToComposer.d.ts +14 -0
  42. package/typings/addRootFieldResolver.d.cts +26 -0
  43. package/typings/addRootFieldResolver.d.ts +26 -0
  44. package/typings/bundle.d.cts +34 -0
  45. package/typings/bundle.d.ts +34 -0
  46. package/typings/directives.d.cts +54 -0
  47. package/typings/directives.d.ts +54 -0
  48. package/typings/getComposerFromJSONSchema.d.cts +13 -0
  49. package/{getComposerFromJSONSchema.d.ts → typings/getComposerFromJSONSchema.d.ts} +7 -4
  50. package/typings/getDereferencedJSONSchemaFromOperations.d.cts +14 -0
  51. package/{getDereferencedJSONSchemaFromOperations.d.ts → typings/getDereferencedJSONSchemaFromOperations.d.ts} +5 -3
  52. package/typings/getGraphQLSchemaFromDereferencedJSONSchema.d.cts +5 -0
  53. package/typings/getGraphQLSchemaFromDereferencedJSONSchema.d.ts +5 -0
  54. package/typings/getJSONSchemaStringFormatScalarMap.d.cts +2 -0
  55. package/typings/getJSONSchemaStringFormatScalarMap.d.ts +2 -0
  56. package/typings/getReferencedJSONSchemaFromOperations.d.cts +16 -0
  57. package/{getReferencedJSONSchemaFromOperations.d.ts → typings/getReferencedJSONSchemaFromOperations.d.ts} +6 -4
  58. package/typings/getTypeResolverFromOutputTCs.d.cts +7 -0
  59. package/typings/getTypeResolverFromOutputTCs.d.ts +7 -0
  60. package/typings/getUnionTypeComposers.d.cts +24 -0
  61. package/typings/getUnionTypeComposers.d.ts +24 -0
  62. package/{getStringScalarWithMinMaxLength.d.ts → typings/getValidTypeName.d.cts} +4 -3
  63. package/typings/index.d.cts +9 -0
  64. package/typings/index.d.ts +9 -0
  65. package/typings/loadGraphQLSchemaFromJSONSchemas.d.cts +3 -0
  66. package/typings/loadGraphQLSchemaFromJSONSchemas.d.ts +3 -0
  67. package/typings/resolveDataByUnionInputType.d.cts +2 -0
  68. package/typings/resolveDataByUnionInputType.d.ts +2 -0
  69. package/typings/scalars.d.cts +4 -0
  70. package/typings/scalars.d.ts +4 -0
  71. package/typings/types.d.cts +76 -0
  72. package/typings/types.d.ts +76 -0
  73. package/typings/utils.d.cts +15 -0
  74. package/{utils.d.ts → typings/utils.d.ts} +1 -1
  75. package/addExecutionLogicToComposer.d.ts +0 -15
  76. package/bundle.d.ts +0 -39
  77. package/getGenericJSONScalar.d.ts +0 -8
  78. package/getGraphQLSchemaFromDereferencedJSONSchema.d.ts +0 -5
  79. package/getJSONSchemaStringFormatScalarMap.d.ts +0 -3
  80. package/getTypeResolverFromOutputTCs.d.ts +0 -4
  81. package/getUnionTypeComposers.d.ts +0 -21
  82. package/getValidateFnForSchemaPath.d.ts +0 -3
  83. package/index.d.ts +0 -9
  84. package/index.js +0 -1890
  85. package/index.mjs +0 -1877
  86. package/loadGraphQLSchemaFromJSONSchemas.d.ts +0 -2
  87. package/resolveDataByUnionInputType.d.ts +0 -3
  88. package/types.d.ts +0 -63
  89. package/{getValidTypeName.d.ts → typings/getValidTypeName.d.ts} +1 -1
package/index.js DELETED
@@ -1,1890 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- const utils = require('@graphql-mesh/utils');
8
- const toJsonSchema = _interopDefault(require('to-json-schema'));
9
- const jsonMachete = require('json-machete');
10
- const stringInterpolation = require('@graphql-mesh/string-interpolation');
11
- const crossHelpers = require('@graphql-mesh/cross-helpers');
12
- const graphql = require('graphql');
13
- const graphqlCompose = require('graphql-compose');
14
- const utils$1 = require('@graphql-tools/utils');
15
- const urlJoin = _interopDefault(require('url-join'));
16
- const qs = require('qs');
17
- const lodashSet = _interopDefault(require('lodash.set'));
18
- const graphqlScalars = require('graphql-scalars');
19
- const Ajv = _interopDefault(require('ajv'));
20
- const addFormats = _interopDefault(require('ajv-formats'));
21
- const pascalCase = require('pascal-case');
22
- const fetch = require('@whatwg-node/fetch');
23
-
24
- function isPubSubOperationConfig(operationConfig) {
25
- return 'pubsubTopic' in operationConfig;
26
- }
27
- function getOperationMetadata(operationConfig) {
28
- let httpMethod;
29
- let operationType;
30
- let rootTypeName;
31
- if (isPubSubOperationConfig(operationConfig)) {
32
- httpMethod = null;
33
- operationType = 'subscription';
34
- rootTypeName = 'Subscription';
35
- }
36
- else {
37
- httpMethod = operationConfig.method;
38
- // Fix compability with Mesh handler
39
- operationType = operationConfig.type.toLowerCase();
40
- if (!httpMethod) {
41
- if (operationType === 'mutation') {
42
- httpMethod = 'POST';
43
- }
44
- else {
45
- httpMethod = 'GET';
46
- }
47
- }
48
- if (!rootTypeName) {
49
- if (httpMethod === 'GET') {
50
- rootTypeName = 'Query';
51
- }
52
- }
53
- rootTypeName = operationType === 'query' ? 'Query' : 'Mutation';
54
- }
55
- return {
56
- httpMethod,
57
- operationType,
58
- rootTypeName,
59
- fieldName: operationConfig.field,
60
- };
61
- }
62
- function cleanObject(obj) {
63
- if (typeof obj === 'object' && obj != null) {
64
- const newObj = Array.isArray(obj) ? [] : {};
65
- for (const key in obj) {
66
- const newObjForKey = cleanObject(obj[key]);
67
- if (newObjForKey != null) {
68
- newObj[key] = newObjForKey;
69
- }
70
- }
71
- return newObj;
72
- }
73
- return obj;
74
- }
75
- function isFileUpload(obj) {
76
- return typeof obj.createReadStream === 'function';
77
- }
78
-
79
- const anySchema = {
80
- title: 'Any',
81
- anyOf: [
82
- {
83
- type: 'object',
84
- additionalProperties: true,
85
- },
86
- {
87
- type: 'string',
88
- },
89
- {
90
- type: 'number',
91
- },
92
- {
93
- type: 'boolean',
94
- },
95
- ],
96
- };
97
- async function handleOperationResponseConfig(operationResponseConfig, { schemaHeaders, cwd, fetchFn, logger = new utils.DefaultLogger('handleOperationResponseConfig'), }) {
98
- if (operationResponseConfig.responseSchema) {
99
- const schema = typeof operationResponseConfig.responseSchema === 'string'
100
- ? {
101
- $ref: operationResponseConfig.responseSchema,
102
- title: operationResponseConfig.responseTypeName,
103
- }
104
- : operationResponseConfig.responseSchema;
105
- if (operationResponseConfig.responseSample) {
106
- schema.examples = schema.examples || [operationResponseConfig.responseSample];
107
- }
108
- return schema;
109
- }
110
- else if (operationResponseConfig.responseSample) {
111
- const sample = typeof operationResponseConfig.responseSample === 'object'
112
- ? operationResponseConfig.responseSample
113
- : await utils.readFileOrUrl(operationResponseConfig.responseSample, {
114
- cwd,
115
- fetch: fetchFn,
116
- logger,
117
- importFn: utils.defaultImportFn,
118
- headers: schemaHeaders,
119
- }).catch((e) => {
120
- throw new Error(`responseSample - ${e.message}`);
121
- });
122
- const generatedSchema = toJsonSchema(sample, {
123
- required: false,
124
- objects: {
125
- additionalProperties: false,
126
- },
127
- strings: {
128
- detectFormat: true,
129
- },
130
- arrays: {
131
- mode: 'first',
132
- },
133
- });
134
- generatedSchema.title = operationResponseConfig.responseTypeName;
135
- generatedSchema.examples = [sample];
136
- return generatedSchema;
137
- }
138
- else {
139
- const generatedSchema = operationResponseConfig.responseTypeName
140
- ? {
141
- ...anySchema,
142
- title: operationResponseConfig.responseTypeName,
143
- }
144
- : anySchema;
145
- return generatedSchema;
146
- }
147
- }
148
- async function getReferencedJSONSchemaFromOperations({ operations, cwd, schemaHeaders, ignoreErrorResponses, logger = new utils.DefaultLogger('getReferencedJSONSchemaFromOperations'), fetchFn, }) {
149
- const finalJsonSchema = {
150
- type: 'object',
151
- title: '_schema',
152
- properties: {},
153
- required: ['query'],
154
- };
155
- for (const operationConfig of operations) {
156
- const { operationType, rootTypeName, fieldName } = getOperationMetadata(operationConfig);
157
- const rootTypeDefinition = (finalJsonSchema.properties[operationType] = finalJsonSchema.properties[operationType] || {
158
- type: 'object',
159
- title: rootTypeName,
160
- properties: {},
161
- });
162
- rootTypeDefinition.properties = rootTypeDefinition.properties || {};
163
- if ('responseByStatusCode' in operationConfig) {
164
- rootTypeDefinition.properties[fieldName] = rootTypeDefinition.properties[fieldName] || {};
165
- const statusCodeOneOfIndexMap = {};
166
- const responseSchemas = [];
167
- for (const statusCode in operationConfig.responseByStatusCode) {
168
- if (ignoreErrorResponses && !statusCode.startsWith('2')) {
169
- continue;
170
- }
171
- const responseOperationConfig = operationConfig.responseByStatusCode[statusCode];
172
- const responseOperationSchema = await handleOperationResponseConfig(responseOperationConfig, {
173
- cwd,
174
- schemaHeaders,
175
- fetchFn,
176
- logger,
177
- });
178
- statusCodeOneOfIndexMap[statusCode] = responseSchemas.length;
179
- responseOperationSchema.title = responseOperationSchema.title || `${fieldName}_${statusCode}_response`;
180
- responseSchemas.push(responseOperationSchema);
181
- }
182
- if (responseSchemas.length === 1) {
183
- rootTypeDefinition.properties[fieldName] = responseSchemas[0];
184
- }
185
- else if (responseSchemas.length === 0) {
186
- rootTypeDefinition.properties[fieldName] = anySchema;
187
- }
188
- else {
189
- rootTypeDefinition.properties[fieldName] = {
190
- $comment: `statusCodeOneOfIndexMap:${JSON.stringify(statusCodeOneOfIndexMap)}`,
191
- title: fieldName + '_response',
192
- oneOf: responseSchemas,
193
- };
194
- }
195
- }
196
- else {
197
- rootTypeDefinition.properties[fieldName] = await handleOperationResponseConfig(operationConfig, {
198
- cwd,
199
- schemaHeaders,
200
- fetchFn,
201
- logger,
202
- });
203
- }
204
- const rootTypeInputPropertyName = operationType + 'Input';
205
- const rootInputTypeName = rootTypeName + 'Input';
206
- const rootTypeInputTypeDefinition = (finalJsonSchema.properties[rootTypeInputPropertyName] = finalJsonSchema
207
- .properties[rootTypeInputPropertyName] || {
208
- type: 'object',
209
- title: rootInputTypeName,
210
- properties: {},
211
- });
212
- if ('binary' in operationConfig) {
213
- const generatedSchema = {
214
- title: operationConfig.requestTypeName || 'File',
215
- type: 'file',
216
- };
217
- rootTypeInputTypeDefinition.properties[fieldName] = generatedSchema;
218
- }
219
- else if ('requestSchema' in operationConfig && operationConfig.requestSchema) {
220
- rootTypeInputTypeDefinition.properties[fieldName] =
221
- typeof operationConfig.requestSchema === 'string'
222
- ? {
223
- $ref: operationConfig.requestSchema,
224
- title: operationConfig.requestTypeName,
225
- }
226
- : operationConfig.requestSchema;
227
- if (operationConfig.requestSample) {
228
- rootTypeInputTypeDefinition.properties[fieldName].examples = rootTypeInputTypeDefinition.properties[fieldName]
229
- .examples || [operationConfig.requestSample];
230
- }
231
- }
232
- else if ('requestSample' in operationConfig) {
233
- const sample = typeof operationConfig.requestSample === 'object'
234
- ? operationConfig.requestSample
235
- : await utils.readFileOrUrl(operationConfig.requestSample, {
236
- cwd,
237
- headers: schemaHeaders,
238
- fetch: fetchFn,
239
- logger,
240
- importFn: utils.defaultImportFn,
241
- }).catch((e) => {
242
- throw new Error(`requestSample:${operationConfig.requestSample} cannot be read - ${e.message}`);
243
- });
244
- const generatedSchema = toJsonSchema(sample, {
245
- required: false,
246
- objects: {
247
- additionalProperties: false,
248
- },
249
- strings: {
250
- detectFormat: true,
251
- },
252
- arrays: {
253
- mode: 'first',
254
- },
255
- });
256
- generatedSchema.title = operationConfig.requestTypeName;
257
- generatedSchema.examples = [sample];
258
- rootTypeInputTypeDefinition.properties[fieldName] = generatedSchema;
259
- }
260
- }
261
- return finalJsonSchema;
262
- }
263
-
264
- async function getDereferencedJSONSchemaFromOperations({ operations, cwd = crossHelpers.process.cwd(), logger, fetchFn, schemaHeaders, ignoreErrorResponses, noDeduplication = false, }) {
265
- const referencedJSONSchema = await getReferencedJSONSchemaFromOperations({
266
- operations,
267
- cwd,
268
- schemaHeaders,
269
- ignoreErrorResponses,
270
- fetchFn,
271
- });
272
- logger.debug(`Dereferencing JSON Schema to resolve all $refs`);
273
- const schemaHeadersFactory = stringInterpolation.getInterpolatedHeadersFactory(schemaHeaders);
274
- const fullyDeferencedSchema = await jsonMachete.dereferenceObject(referencedJSONSchema, {
275
- cwd,
276
- fetchFn,
277
- logger,
278
- headers: schemaHeadersFactory({ env: crossHelpers.process.env }),
279
- });
280
- logger.debug(`Healing JSON Schema`);
281
- const healedSchema = await jsonMachete.healJSONSchema(fullyDeferencedSchema, { noDeduplication });
282
- return healedSchema;
283
- }
284
-
285
- function resolveDataByUnionInputType(data, type, schemaComposer) {
286
- var _a;
287
- if (data) {
288
- if (graphql.isListType(type)) {
289
- return utils$1.asArray(data).map(elem => resolveDataByUnionInputType(elem, type.ofType, schemaComposer));
290
- }
291
- if (graphql.isNonNullType(type)) {
292
- return resolveDataByUnionInputType(data, type.ofType, schemaComposer);
293
- }
294
- if (graphql.isInputObjectType(type)) {
295
- const fieldMap = type.getFields();
296
- const isOneOf = schemaComposer.getAnyTC(type).getDirectiveByName('oneOf');
297
- data = utils$1.asArray(data)[0];
298
- for (const propertyName in data) {
299
- const fieldName = utils.sanitizeNameForGraphQL(propertyName);
300
- const field = fieldMap[fieldName];
301
- if (field) {
302
- if (isOneOf) {
303
- const resolvedData = resolveDataByUnionInputType(data[fieldName], field.type, schemaComposer);
304
- return resolvedData;
305
- }
306
- const realFieldName = ((_a = field.extensions) === null || _a === void 0 ? void 0 : _a.propertyName) || fieldName;
307
- data[realFieldName] = resolveDataByUnionInputType(data[fieldName], field.type, schemaComposer);
308
- }
309
- }
310
- }
311
- }
312
- return data;
313
- }
314
-
315
- const defaultQsOptions = {
316
- indices: false,
317
- };
318
- const isListTypeOrNonNullListType = utils$1.memoize1(function isListTypeOrNonNullListType(type) {
319
- if (graphql.isNonNullType(type)) {
320
- return graphql.isListType(type.ofType);
321
- }
322
- return graphql.isListType(type);
323
- });
324
- function createError(message, extensions) {
325
- return new graphql.GraphQLError(message, undefined, undefined, undefined, undefined, undefined, extensions);
326
- }
327
- function linkResolver(linkObjArgs, actualResolver, root, args, context, info) {
328
- for (const argKey in linkObjArgs) {
329
- const argInterpolation = linkObjArgs[argKey];
330
- const actualValue = stringInterpolation.stringInterpolator.parse(argInterpolation, {
331
- root,
332
- args,
333
- context,
334
- info,
335
- env: crossHelpers.process.env,
336
- });
337
- lodashSet(args, argKey, actualValue);
338
- lodashSet(args, `input.${argKey}`, actualValue);
339
- }
340
- return actualResolver(root, args, context, info);
341
- }
342
- const responseMetadataType = new graphql.GraphQLObjectType({
343
- name: 'ResponseMetadata',
344
- fields: {
345
- url: { type: graphql.GraphQLString },
346
- method: { type: graphql.GraphQLString },
347
- status: { type: graphql.GraphQLInt },
348
- statusTest: { type: graphql.GraphQLString },
349
- headers: { type: graphqlCompose.GraphQLJSON },
350
- body: { type: graphqlCompose.GraphQLJSON },
351
- },
352
- });
353
- async function addExecutionLogicToComposer(schemaComposer, { fetch: globalFetch, logger, operations, operationHeaders, baseUrl, pubsub: globalPubsub, queryParams, queryStringOptions = {}, }) {
354
- logger.debug(`Attaching execution logic to the schema`);
355
- const qsOptions = { ...defaultQsOptions, ...queryStringOptions };
356
- for (const operationConfig of operations) {
357
- const { httpMethod, rootTypeName, fieldName } = getOperationMetadata(operationConfig);
358
- const operationLogger = logger.child(`${rootTypeName}.${fieldName}`);
359
- const interpolationStrings = [
360
- ...Object.values(operationHeaders || {}),
361
- ...Object.values(queryParams || {}),
362
- baseUrl,
363
- ];
364
- const rootTypeComposer = schemaComposer[rootTypeName];
365
- const field = rootTypeComposer.getField(fieldName);
366
- if (isPubSubOperationConfig(operationConfig)) {
367
- field.description = operationConfig.description || `PubSub Topic: ${operationConfig.pubsubTopic}`;
368
- field.subscribe = (root, args, context, info) => {
369
- const pubsub = (context === null || context === void 0 ? void 0 : context.pubsub) || globalPubsub;
370
- if (!pubsub) {
371
- return new graphql.GraphQLError(`You should have PubSub defined in either the config or the context!`);
372
- }
373
- const interpolationData = { root, args, context, info, env: crossHelpers.process.env };
374
- const pubsubTopic = stringInterpolation.stringInterpolator.parse(operationConfig.pubsubTopic, interpolationData);
375
- operationLogger.debug(`=> Subscribing to pubSubTopic: ${pubsubTopic}`);
376
- return pubsub.asyncIterator(pubsubTopic);
377
- };
378
- field.resolve = root => {
379
- operationLogger.debug('Received ', root, ' from ', operationConfig.pubsubTopic);
380
- return root;
381
- };
382
- interpolationStrings.push(operationConfig.pubsubTopic);
383
- }
384
- else if (operationConfig.path) {
385
- if (crossHelpers.process.env.DEBUG) {
386
- field.description = `
387
- ***Original Description***: ${operationConfig.description || '(none)'}
388
- ***Method***: ${operationConfig.method}
389
- ***Base URL***: ${baseUrl}
390
- ***Path***: ${operationConfig.path}
391
- `;
392
- }
393
- else {
394
- field.description = operationConfig.description;
395
- }
396
- field.resolve = async (root, args, context) => {
397
- var _a, _b, _c;
398
- operationLogger.debug(`=> Resolving`);
399
- const interpolationData = { root, args, context, env: crossHelpers.process.env };
400
- const interpolatedBaseUrl = stringInterpolation.stringInterpolator.parse(baseUrl, interpolationData);
401
- const interpolatedPath = stringInterpolation.stringInterpolator.parse(operationConfig.path, interpolationData);
402
- let fullPath = urlJoin(interpolatedBaseUrl, interpolatedPath);
403
- const nonInterpolatedHeaders = {
404
- ...operationHeaders,
405
- ...operationConfig === null || operationConfig === void 0 ? void 0 : operationConfig.headers,
406
- };
407
- const headers = {};
408
- for (const headerName in nonInterpolatedHeaders) {
409
- const nonInterpolatedValue = nonInterpolatedHeaders[headerName];
410
- const interpolatedValue = stringInterpolation.stringInterpolator.parse(nonInterpolatedValue, interpolationData);
411
- if (interpolatedValue) {
412
- headers[headerName] = interpolatedValue;
413
- }
414
- }
415
- const requestInit = {
416
- method: httpMethod,
417
- headers,
418
- };
419
- if (queryParams) {
420
- const interpolatedQueryParams = {};
421
- for (const queryParamName in queryParams) {
422
- interpolatedQueryParams[queryParamName] = stringInterpolation.stringInterpolator.parse(queryParams[queryParamName], interpolationData);
423
- }
424
- const queryParamsString = qs.stringify(interpolatedQueryParams, qsOptions);
425
- fullPath += fullPath.includes('?') ? '&' : '?';
426
- fullPath += queryParamsString;
427
- }
428
- // Handle binary data
429
- if ('binary' in operationConfig) {
430
- const binaryUpload = await args.input;
431
- if (isFileUpload(binaryUpload)) {
432
- const readable = binaryUpload.createReadStream();
433
- const chunks = [];
434
- for await (const chunk of readable) {
435
- for (const byte of chunk) {
436
- chunks.push(byte);
437
- }
438
- }
439
- requestInit.body = new Uint8Array(chunks);
440
- const [, contentType] = Object.entries(headers).find(([key]) => key.toLowerCase() === 'content-type') || [];
441
- if (!contentType) {
442
- headers['content-type'] = binaryUpload.mimetype;
443
- }
444
- }
445
- requestInit.body = binaryUpload;
446
- }
447
- else {
448
- if (operationConfig.requestBaseBody != null) {
449
- args.input = args.input || {};
450
- for (const key in operationConfig.requestBaseBody) {
451
- const configValue = operationConfig.requestBaseBody[key];
452
- if (typeof configValue === 'string') {
453
- const value = stringInterpolation.stringInterpolator.parse(configValue, interpolationData);
454
- lodashSet(args.input, key, value);
455
- }
456
- else {
457
- args.input[key] = configValue;
458
- }
459
- }
460
- }
461
- // Resolve union input
462
- const input = (args.input = resolveDataByUnionInputType(cleanObject(args.input), (_c = (_b = (_a = field.args) === null || _a === void 0 ? void 0 : _a.input) === null || _b === void 0 ? void 0 : _b.type) === null || _c === void 0 ? void 0 : _c.getType(), schemaComposer));
463
- if (input != null) {
464
- switch (httpMethod) {
465
- case 'GET':
466
- case 'HEAD':
467
- case 'CONNECT':
468
- case 'OPTIONS':
469
- case 'TRACE': {
470
- fullPath += fullPath.includes('?') ? '&' : '?';
471
- fullPath += qs.stringify(input, qsOptions);
472
- break;
473
- }
474
- case 'POST':
475
- case 'PUT':
476
- case 'PATCH':
477
- case 'DELETE': {
478
- const [, contentType] = Object.entries(headers).find(([key]) => key.toLowerCase() === 'content-type') || [];
479
- if (contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('application/x-www-form-urlencoded')) {
480
- requestInit.body = qs.stringify(input, qsOptions);
481
- }
482
- else {
483
- requestInit.body = JSON.stringify(input);
484
- }
485
- break;
486
- }
487
- default:
488
- return createError(`Unknown HTTP Method: ${httpMethod}`, {
489
- url: fullPath,
490
- method: httpMethod,
491
- });
492
- }
493
- }
494
- }
495
- // Delete unused queryparams
496
- const [actualPath, queryString] = fullPath.split('?');
497
- if (queryString) {
498
- const queryParams = qs.parse(queryString);
499
- const cleanedQueryParams = cleanObject(queryParams);
500
- fullPath = actualPath + '?' + qs.stringify(cleanedQueryParams, qsOptions);
501
- }
502
- operationLogger.debug(`=> Fetching `, fullPath, `=>`, requestInit);
503
- const fetch = (context === null || context === void 0 ? void 0 : context.fetch) || globalFetch;
504
- if (!fetch) {
505
- return createError(`You should have fetch defined in either the config or the context!`, {
506
- url: fullPath,
507
- method: httpMethod,
508
- });
509
- }
510
- const response = await fetch(fullPath, requestInit);
511
- // If return type is a file
512
- if (field.type.getTypeName() === 'File') {
513
- return response.blob();
514
- }
515
- const responseText = await response.text();
516
- operationLogger.debug(`=> Received`, {
517
- headers: response.headers,
518
- text: responseText,
519
- });
520
- let responseJson;
521
- try {
522
- responseJson = JSON.parse(responseText);
523
- }
524
- catch (error) {
525
- const returnNamedGraphQLType = graphql.getNamedType(field.type.getType());
526
- // The result might be defined as scalar
527
- if (graphql.isScalarType(returnNamedGraphQLType)) {
528
- operationLogger.debug(` => Return type is not a JSON so returning ${responseText}`);
529
- return responseText;
530
- }
531
- else if (response.status === 204) {
532
- responseJson = {};
533
- }
534
- else {
535
- return createError(`Unexpected response`, {
536
- url: fullPath,
537
- method: httpMethod,
538
- responseText,
539
- error,
540
- });
541
- }
542
- }
543
- if (!response.status.toString().startsWith('2')) {
544
- const returnNamedGraphQLType = graphql.getNamedType(field.type.getType());
545
- if (!graphql.isUnionType(returnNamedGraphQLType)) {
546
- return createError(`HTTP Error: ${response.status}`, {
547
- url: fullPath,
548
- method: httpMethod,
549
- ...(response.statusText ? { status: response.statusText } : {}),
550
- responseJson,
551
- });
552
- }
553
- }
554
- operationLogger.debug(`Returning `, responseJson);
555
- // Sometimes API returns an array but the return type is not an array
556
- const isListReturnType = isListTypeOrNonNullListType(field.type.getType());
557
- const isArrayResponse = Array.isArray(responseJson);
558
- if (isListReturnType && !isArrayResponse) {
559
- operationLogger.debug(`Response is not array but return type is list. Normalizing the response`);
560
- responseJson = [responseJson];
561
- }
562
- if (!isListReturnType && isArrayResponse) {
563
- operationLogger.debug(`Response is array but return type is not list. Normalizing the response`);
564
- responseJson = responseJson[0];
565
- }
566
- const addResponseMetadata = (obj) => {
567
- return {
568
- ...obj,
569
- $url: fullPath,
570
- $method: httpMethod,
571
- $request: {
572
- query: {
573
- ...obj,
574
- ...args,
575
- ...args.input,
576
- },
577
- path: {
578
- ...obj,
579
- ...args,
580
- },
581
- header: requestInit.headers,
582
- },
583
- $response: {
584
- url: fullPath,
585
- method: httpMethod,
586
- status: response.status,
587
- statusText: response.statusText,
588
- headers: utils.getHeadersObj(response.headers),
589
- body: obj,
590
- },
591
- };
592
- };
593
- operationLogger.debug(`Adding response metadata to the response object`);
594
- return Array.isArray(responseJson)
595
- ? responseJson.map(obj => addResponseMetadata(obj))
596
- : addResponseMetadata(responseJson);
597
- };
598
- interpolationStrings.push(...Object.values(operationConfig.headers || {}));
599
- interpolationStrings.push(operationConfig.path);
600
- if ('links' in operationConfig) {
601
- for (const linkName in operationConfig.links) {
602
- const linkObj = operationConfig.links[linkName];
603
- const typeTC = schemaComposer.getOTC(field.type.getTypeName());
604
- typeTC.addFields({
605
- [linkName]: () => {
606
- const targetField = schemaComposer.Query.getField(linkObj.fieldName);
607
- return {
608
- ...targetField,
609
- args: {},
610
- description: linkObj.description || targetField.description,
611
- resolve: (root, args, context, info) => linkResolver(linkObj.args, targetField.resolve, root, args, context, info),
612
- };
613
- },
614
- });
615
- }
616
- }
617
- if ('exposeResponseMetadata' in operationConfig && operationConfig.exposeResponseMetadata) {
618
- const typeTC = schemaComposer.getOTC(field.type.getTypeName());
619
- typeTC.addFields({
620
- _response: {
621
- type: responseMetadataType,
622
- resolve: root => root.$response,
623
- },
624
- });
625
- }
626
- if ('responseByStatusCode' in operationConfig) {
627
- const unionOrSingleTC = schemaComposer.getAnyTC(graphql.getNamedType(field.type.getType()));
628
- const types = 'getTypes' in unionOrSingleTC ? unionOrSingleTC.getTypes() : [unionOrSingleTC];
629
- const statusCodeOneOfIndexMap = unionOrSingleTC.getExtension('statusCodeOneOfIndexMap') || {};
630
- for (const statusCode in operationConfig.responseByStatusCode) {
631
- const responseConfig = operationConfig.responseByStatusCode[statusCode];
632
- if (responseConfig.links || responseConfig.exposeResponseMetadata) {
633
- const typeTCThunked = types[statusCodeOneOfIndexMap[statusCode] || 0];
634
- const typeTC = schemaComposer.getAnyTC(typeTCThunked.getTypeName());
635
- if ('addFieldArgs' in typeTC) {
636
- if (responseConfig.exposeResponseMetadata) {
637
- typeTC.addFields({
638
- _response: {
639
- type: responseMetadataType,
640
- resolve: root => root.$response,
641
- },
642
- });
643
- }
644
- for (const linkName in responseConfig.links || []) {
645
- typeTC.addFields({
646
- [linkName]: () => {
647
- const linkObj = responseConfig.links[linkName];
648
- const targetField = schemaComposer.Query.getField(linkObj.fieldName);
649
- return {
650
- ...targetField,
651
- args: {},
652
- description: linkObj.description || targetField.description,
653
- resolve: (root, args, context, info) => linkResolver(linkObj.args, targetField.resolve, root, args, context, info),
654
- };
655
- },
656
- });
657
- }
658
- }
659
- }
660
- }
661
- }
662
- }
663
- const { args: globalArgs } = stringInterpolation.parseInterpolationStrings(interpolationStrings, operationConfig.argTypeMap);
664
- rootTypeComposer.addFieldArgs(fieldName, globalArgs);
665
- }
666
- logger.debug(`Building the executable schema.`);
667
- return schemaComposer;
668
- }
669
-
670
- function getValidTypeName({ schemaComposer, isInput, subSchema, }) {
671
- const sanitizedName = utils.sanitizeNameForGraphQL(isInput ? subSchema.title + '_Input' : subSchema.title);
672
- if (schemaComposer.has(sanitizedName)) {
673
- let i = 2;
674
- while (schemaComposer.has(sanitizedName + i)) {
675
- i++;
676
- }
677
- return sanitizedName + i;
678
- }
679
- return sanitizedName;
680
- }
681
-
682
- function getStringScalarWithMinMaxLength({ schemaComposer, subSchema, }) {
683
- const name = getValidTypeName({
684
- schemaComposer,
685
- isInput: false,
686
- subSchema,
687
- });
688
- function coerceString(value) {
689
- if (value != null) {
690
- const vStr = value.toString();
691
- if (typeof subSchema.minLength !== 'undefined' && vStr.length < subSchema.minLength) {
692
- throw new Error(`${name} cannot be less than ${subSchema.minLength} but given ${vStr}`);
693
- }
694
- if (typeof subSchema.maxLength !== 'undefined' && vStr.length > subSchema.maxLength) {
695
- throw new Error(`${name} cannot be more than ${subSchema.maxLength} but given ${vStr}`);
696
- }
697
- return vStr;
698
- }
699
- }
700
- return schemaComposer.createScalarTC({
701
- name,
702
- description: subSchema.description,
703
- serialize: coerceString,
704
- parseValue: coerceString,
705
- parseLiteral: ast => {
706
- if ('value' in ast) {
707
- return coerceString(ast.value);
708
- }
709
- return null;
710
- },
711
- extensions: {
712
- codegenScalarType: 'string',
713
- },
714
- });
715
- }
716
-
717
- const JSONSchemaStringFormats = [
718
- 'date',
719
- 'hostname',
720
- 'regex',
721
- 'json-pointer',
722
- 'relative-json-pointer',
723
- 'uri-reference',
724
- 'uri-template',
725
- ];
726
- function getJSONSchemaStringFormatScalarMap(ajv) {
727
- const map = new Map();
728
- for (const format of JSONSchemaStringFormats) {
729
- const schema = {
730
- type: 'string',
731
- format,
732
- };
733
- let validate;
734
- try {
735
- validate = ajv.compile(schema);
736
- }
737
- catch (e) {
738
- validate = (value) => ajv.validate(schema, value);
739
- }
740
- const coerceString = (value) => {
741
- if (validate(value)) {
742
- return value;
743
- }
744
- throw new Error(`Expected ${format} but got: ${value}`);
745
- };
746
- const scalar = new graphql.GraphQLScalarType({
747
- name: pascalCase.pascalCase(format),
748
- description: `Represents ${format} values`,
749
- serialize: coerceString,
750
- parseValue: coerceString,
751
- parseLiteral: ast => {
752
- if (ast.kind === graphql.Kind.STRING) {
753
- return coerceString(ast.value);
754
- }
755
- throw new Error(`Expected string in ${format} format but got: ${ast.value}`);
756
- },
757
- extensions: {
758
- codegenScalarType: 'string',
759
- },
760
- });
761
- map.set(format, scalar);
762
- }
763
- return map;
764
- }
765
-
766
- function getTypeResolverFromOutputTCs(ajv, outputTypeComposers, statusCodeOneOfIndexMap) {
767
- const statusCodeTypeMap = new Map();
768
- for (const statusCode in statusCodeOneOfIndexMap) {
769
- statusCodeTypeMap.set(statusCode.toString(), outputTypeComposers[statusCodeOneOfIndexMap[statusCode]]);
770
- }
771
- return function resolveType(data, context, info) {
772
- if (data.__typename) {
773
- return data.__typename;
774
- }
775
- else if (data.resourceType) {
776
- return data.resourceType;
777
- }
778
- if (data.$response && statusCodeOneOfIndexMap) {
779
- const responseData = data.$response;
780
- const type = statusCodeTypeMap.get(responseData.status.toString()) || statusCodeTypeMap.get('default');
781
- if (type) {
782
- if ('getFields' in type) {
783
- return type.getTypeName();
784
- }
785
- else {
786
- return type.getResolveType()(data, context, info, type.getType());
787
- }
788
- }
789
- }
790
- const validationErrors = {};
791
- for (const outputTypeComposer of outputTypeComposers) {
792
- const validateFn = outputTypeComposer.getExtension('validateWithJSONSchema');
793
- if (validateFn) {
794
- const isValid = validateFn(data);
795
- const typeName = outputTypeComposer.getTypeName();
796
- if (isValid) {
797
- if ('getFields' in outputTypeComposer) {
798
- return outputTypeComposer.getTypeName();
799
- }
800
- else {
801
- return outputTypeComposer.getResolveType()(data, context, info, outputTypeComposer.getType());
802
- }
803
- }
804
- validationErrors[typeName] = ajv.errors || validateFn.errors;
805
- }
806
- }
807
- if (data.$response) {
808
- const responseData = data.$response;
809
- const error = new graphql.GraphQLError(`HTTP Error: ${responseData.status}`, undefined, undefined, undefined, undefined, undefined, {
810
- ...responseData,
811
- responseJson: data,
812
- });
813
- console.error(error);
814
- return error;
815
- }
816
- const error = new graphql.GraphQLError(`Received data doesn't met the union`, null, null, null, null, null, {
817
- validationErrors,
818
- });
819
- console.error(error);
820
- return error;
821
- };
822
- }
823
-
824
- const ONE_OF_DEFINITION = /* GraphQL */ `
825
- directive @oneOf on INPUT_OBJECT | FIELD_DEFINITION
826
- `;
827
- function getUnionTypeComposers({ schemaComposer, ajv, typeComposersList, subSchema, generateInterfaceFromSharedFields, statusCodeOneOfIndexMap, }) {
828
- if (typeComposersList.length === 1) {
829
- return typeComposersList[0];
830
- }
831
- const unionInputFields = {};
832
- const outputTypeComposers = [];
833
- typeComposersList.forEach(typeComposers => {
834
- const { input, output } = typeComposers;
835
- if (graphqlCompose.isSomeInputTypeComposer(output)) {
836
- const containerTypeName = `${output.getTypeName()}_container`;
837
- outputTypeComposers.push(schemaComposer.getOrCreateOTC(containerTypeName, otc => otc.addFields({
838
- [output.getTypeName()]: {
839
- type: output,
840
- resolve: root => root,
841
- },
842
- })));
843
- }
844
- else {
845
- outputTypeComposers.push(output);
846
- }
847
- unionInputFields[input.getTypeName()] = {
848
- type: input,
849
- };
850
- });
851
- const input = schemaComposer.createInputTC({
852
- name: getValidTypeName({
853
- schemaComposer,
854
- isInput: true,
855
- subSchema,
856
- }),
857
- description: subSchema.description,
858
- fields: unionInputFields,
859
- });
860
- if (!schemaComposer.hasDirective('oneOf')) {
861
- schemaComposer.addTypeDefs(ONE_OF_DEFINITION);
862
- }
863
- input.setDirectives([
864
- {
865
- name: 'oneOf',
866
- args: {},
867
- },
868
- ]);
869
- let output;
870
- let sharedFields;
871
- if (generateInterfaceFromSharedFields) {
872
- for (const typeComposer of outputTypeComposers) {
873
- const fieldMap = typeComposer.getFields();
874
- if (!sharedFields) {
875
- sharedFields = { ...fieldMap };
876
- }
877
- else {
878
- for (const potentialSharedFieldName in sharedFields) {
879
- if (!(potentialSharedFieldName in fieldMap &&
880
- fieldMap[potentialSharedFieldName].type.getTypeName() ===
881
- sharedFields[potentialSharedFieldName].type.getTypeName())) {
882
- sharedFields[potentialSharedFieldName] = undefined;
883
- delete sharedFields[potentialSharedFieldName];
884
- }
885
- }
886
- }
887
- }
888
- }
889
- const resolveType = getTypeResolverFromOutputTCs(ajv, outputTypeComposers, statusCodeOneOfIndexMap);
890
- if (sharedFields && Object.keys(sharedFields).length > 0) {
891
- output = schemaComposer.createInterfaceTC({
892
- name: getValidTypeName({
893
- schemaComposer,
894
- isInput: false,
895
- subSchema,
896
- }),
897
- description: subSchema.description,
898
- fields: sharedFields,
899
- resolveType,
900
- extensions: {
901
- statusCodeOneOfIndexMap,
902
- },
903
- });
904
- for (const typeComposer of outputTypeComposers) {
905
- typeComposer.addInterface(output);
906
- // GraphQL removes implementations
907
- schemaComposer.addSchemaMustHaveType(typeComposer);
908
- }
909
- }
910
- else {
911
- // If no shared fields found
912
- output = schemaComposer.createUnionTC({
913
- name: getValidTypeName({
914
- schemaComposer,
915
- isInput: false,
916
- subSchema,
917
- }),
918
- description: subSchema.description,
919
- types: () => {
920
- const possibleTypes = [];
921
- for (const outputTypeComposer of outputTypeComposers) {
922
- if ('getFields' in outputTypeComposer) {
923
- possibleTypes.push(outputTypeComposer);
924
- }
925
- else {
926
- for (const possibleType of outputTypeComposer.getTypes()) {
927
- possibleTypes.push(possibleType);
928
- }
929
- }
930
- }
931
- return possibleTypes;
932
- },
933
- resolveType,
934
- extensions: {
935
- statusCodeOneOfIndexMap,
936
- },
937
- });
938
- }
939
- return {
940
- input,
941
- output,
942
- };
943
- }
944
-
945
- function getGenericJSONScalar({ isInput, subSchema, schemaComposer, validateWithJSONSchema, }) {
946
- function coerceGenericJSONScalar(value) {
947
- if (!validateWithJSONSchema(value)) {
948
- throw new Error(`${crossHelpers.util.inspect(value)} is not valid!`);
949
- }
950
- return value;
951
- }
952
- const name = getValidTypeName({
953
- schemaComposer,
954
- isInput,
955
- subSchema,
956
- });
957
- return schemaComposer.createScalarTC({
958
- name,
959
- description: subSchema.description,
960
- serialize: coerceGenericJSONScalar,
961
- parseValue: coerceGenericJSONScalar,
962
- parseLiteral(...args) {
963
- const value = graphqlCompose.GraphQLJSON.parseLiteral(...args);
964
- return coerceGenericJSONScalar(value);
965
- },
966
- extensions: {
967
- codegenScalarType: 'any',
968
- examples: subSchema.examples,
969
- default: subSchema.default,
970
- },
971
- });
972
- }
973
-
974
- const ajvMemoizedCompile = utils$1.memoize2(function ajvCompile(ajv, jsonSchema) {
975
- const schema = typeof jsonSchema === 'object'
976
- ? {
977
- ...jsonSchema,
978
- $schema: undefined,
979
- }
980
- : jsonSchema;
981
- try {
982
- return ajv.compile(schema);
983
- }
984
- catch (_a) {
985
- // eslint-disable-next-line no-inner-declarations
986
- function validateFn(value) {
987
- return ajv.validate(schema, value);
988
- }
989
- Object.defineProperty(validateFn, 'errors', {
990
- get() {
991
- return ajv.errors;
992
- },
993
- });
994
- return validateFn;
995
- }
996
- });
997
- function getValidateFnForSchemaPath(ajv, path, schema) {
998
- const subSchema = jsonMachete.resolvePath(path, schema);
999
- const fn = function validateFn(data) {
1000
- const ajvValidateFn = ajvMemoizedCompile(ajv, subSchema);
1001
- return ajvValidateFn(data);
1002
- };
1003
- Object.defineProperty(fn, 'errors', {
1004
- get() {
1005
- return ajvMemoizedCompile(ajv, subSchema).errors;
1006
- },
1007
- });
1008
- return fn;
1009
- }
1010
-
1011
- /* eslint-disable no-case-declarations */
1012
- const isListTC = utils$1.memoize1(function isListTC(type) {
1013
- return type instanceof graphqlCompose.ListComposer;
1014
- });
1015
- const GraphQLVoid = new graphql.GraphQLScalarType({
1016
- name: 'Void',
1017
- description: 'Represents empty values',
1018
- serialize: () => '',
1019
- extensions: {
1020
- codegenScalarType: 'void',
1021
- },
1022
- });
1023
- const GraphQLFile = new graphql.GraphQLScalarType({
1024
- name: 'File',
1025
- extensions: {
1026
- codegenScalarType: 'File',
1027
- },
1028
- });
1029
- function getComposerFromJSONSchema(schema, logger, generateInterfaceFromSharedFields = false) {
1030
- const schemaComposer = new graphqlCompose.SchemaComposer();
1031
- const ajv = new Ajv({
1032
- strict: false,
1033
- });
1034
- addFormats(ajv);
1035
- const formatScalarMap = getJSONSchemaStringFormatScalarMap(ajv);
1036
- const futureTasks = new Set();
1037
- return jsonMachete.visitJSONSchema(schema, function mutateFn(subSchema, { path }) {
1038
- logger === null || logger === void 0 ? void 0 : logger.debug(`Processing ${path} for GraphQL Schema`);
1039
- const getTypeComposer = () => {
1040
- var _a, _b, _c, _d, _e;
1041
- if (typeof subSchema === 'boolean') {
1042
- const typeComposer = schemaComposer.getAnyTC(graphqlScalars.GraphQLJSON);
1043
- return subSchema
1044
- ? {
1045
- input: typeComposer,
1046
- output: typeComposer,
1047
- }
1048
- : undefined;
1049
- }
1050
- const validateWithJSONSchema = getValidateFnForSchemaPath(ajv, path, schema);
1051
- if (!subSchema) {
1052
- throw new Error(`Something is wrong with ${path}`);
1053
- }
1054
- if (subSchema.pattern) {
1055
- const scalarType = new graphqlScalars.RegularExpression(getValidTypeName({
1056
- schemaComposer,
1057
- isInput: false,
1058
- subSchema,
1059
- }), new RegExp(subSchema.pattern), {
1060
- description: subSchema.description,
1061
- });
1062
- const typeComposer = schemaComposer.getAnyTC(scalarType);
1063
- return {
1064
- input: typeComposer,
1065
- output: typeComposer,
1066
- };
1067
- }
1068
- if (subSchema.const) {
1069
- const tsTypeName = JSON.stringify(subSchema.const);
1070
- const scalarTypeName = getValidTypeName({
1071
- schemaComposer,
1072
- isInput: false,
1073
- subSchema,
1074
- });
1075
- const scalarType = new graphqlScalars.RegularExpression(scalarTypeName, new RegExp(subSchema.const), {
1076
- description: subSchema.description || `A field whose value is ${tsTypeName}`,
1077
- errorMessage: (_r, v) => `Expected ${tsTypeName} but got ${JSON.stringify(v)}`,
1078
- });
1079
- scalarType.extensions = {
1080
- codegenScalarType: tsTypeName,
1081
- };
1082
- const typeComposer = schemaComposer.createScalarTC(scalarType);
1083
- return {
1084
- input: typeComposer,
1085
- output: typeComposer,
1086
- };
1087
- }
1088
- if (subSchema.enum && subSchema.type !== 'boolean') {
1089
- const values = {};
1090
- for (const value of subSchema.enum) {
1091
- let enumKey = utils.sanitizeNameForGraphQL(value.toString());
1092
- if (enumKey === 'false' || enumKey === 'true' || enumKey === 'null') {
1093
- enumKey = enumKey.toUpperCase();
1094
- }
1095
- if (typeof enumKey === 'string' && enumKey.length === 0) {
1096
- enumKey = '_';
1097
- }
1098
- values[enumKey] = {
1099
- // Falsy values are ignored by GraphQL
1100
- // eslint-disable-next-line no-unneeded-ternary
1101
- value: value ? value : value === null || value === void 0 ? void 0 : value.toString(),
1102
- };
1103
- }
1104
- const typeComposer = schemaComposer.createEnumTC({
1105
- name: getValidTypeName({
1106
- schemaComposer,
1107
- isInput: false,
1108
- subSchema,
1109
- }),
1110
- values,
1111
- description: subSchema.description,
1112
- extensions: {
1113
- examples: subSchema.examples,
1114
- default: subSchema.default,
1115
- },
1116
- });
1117
- return {
1118
- input: typeComposer,
1119
- output: typeComposer,
1120
- };
1121
- }
1122
- if (subSchema.oneOf && !subSchema.properties) {
1123
- let statusCodeOneOfIndexMap;
1124
- if ((_a = subSchema.$comment) === null || _a === void 0 ? void 0 : _a.startsWith('statusCodeOneOfIndexMap:')) {
1125
- const statusCodeOneOfIndexMapStr = subSchema.$comment.replace('statusCodeOneOfIndexMap:', '');
1126
- statusCodeOneOfIndexMap = JSON.parse(statusCodeOneOfIndexMapStr);
1127
- }
1128
- const isPlural = subSchema.oneOf.some(({ output }) => 'ofType' in output);
1129
- if (isPlural) {
1130
- const { input, output } = getUnionTypeComposers({
1131
- schemaComposer,
1132
- ajv,
1133
- typeComposersList: subSchema.oneOf.map(({ input, output }) => ({
1134
- input: input.ofType || input,
1135
- output: output.ofType || output,
1136
- })),
1137
- subSchema,
1138
- generateInterfaceFromSharedFields,
1139
- statusCodeOneOfIndexMap,
1140
- });
1141
- return {
1142
- input: input.getTypePlural(),
1143
- output: output.getTypePlural(),
1144
- };
1145
- }
1146
- return getUnionTypeComposers({
1147
- schemaComposer,
1148
- ajv,
1149
- typeComposersList: subSchema.oneOf,
1150
- subSchema,
1151
- generateInterfaceFromSharedFields,
1152
- statusCodeOneOfIndexMap,
1153
- });
1154
- }
1155
- if (subSchema.allOf && !subSchema.properties) {
1156
- const inputFieldMap = {};
1157
- const fieldMap = {};
1158
- let ableToUseGraphQLInputObjectType = true;
1159
- for (const maybeTypeComposers of subSchema.allOf) {
1160
- const { input: inputTypeComposer, output: outputTypeComposer } = maybeTypeComposers;
1161
- if (inputTypeComposer instanceof graphqlCompose.ScalarTypeComposer) {
1162
- ableToUseGraphQLInputObjectType = false;
1163
- }
1164
- else {
1165
- const inputTypeElemFieldMap = inputTypeComposer.getFields();
1166
- for (const fieldName in inputTypeElemFieldMap) {
1167
- const field = inputTypeElemFieldMap[fieldName];
1168
- inputFieldMap[fieldName] = field;
1169
- }
1170
- }
1171
- if (outputTypeComposer instanceof graphqlCompose.ScalarTypeComposer) {
1172
- fieldMap[outputTypeComposer.getTypeName()] = {
1173
- type: outputTypeComposer,
1174
- resolve: root => root,
1175
- };
1176
- }
1177
- else if (outputTypeComposer instanceof graphqlCompose.UnionTypeComposer) {
1178
- const outputTCElems = outputTypeComposer.getTypes();
1179
- for (const outputTCElem of outputTCElems) {
1180
- const outputTypeElemFieldMap = outputTCElem.getFields();
1181
- for (const fieldName in outputTypeElemFieldMap) {
1182
- const field = outputTypeElemFieldMap[fieldName];
1183
- fieldMap[fieldName] = field;
1184
- }
1185
- }
1186
- }
1187
- else {
1188
- const typeElemFieldMap = outputTypeComposer.getFields();
1189
- for (const fieldName in typeElemFieldMap) {
1190
- const field = typeElemFieldMap[fieldName];
1191
- fieldMap[fieldName] = field;
1192
- }
1193
- }
1194
- }
1195
- let inputTypeComposer;
1196
- const outputTypeComposer = schemaComposer.createObjectTC({
1197
- name: getValidTypeName({
1198
- schemaComposer,
1199
- isInput: false,
1200
- subSchema,
1201
- }),
1202
- description: subSchema.description,
1203
- fields: fieldMap,
1204
- extensions: {
1205
- validateWithJSONSchema,
1206
- examples: subSchema.examples,
1207
- default: subSchema.default,
1208
- },
1209
- });
1210
- if (ableToUseGraphQLInputObjectType) {
1211
- inputTypeComposer = schemaComposer.createInputTC({
1212
- name: getValidTypeName({
1213
- schemaComposer,
1214
- isInput: true,
1215
- subSchema,
1216
- }),
1217
- description: subSchema.description,
1218
- fields: inputFieldMap,
1219
- extensions: {
1220
- examples: subSchema.examples,
1221
- default: subSchema.default,
1222
- },
1223
- });
1224
- }
1225
- else {
1226
- inputTypeComposer = graphqlCompose.isSomeInputTypeComposer(outputTypeComposer)
1227
- ? outputTypeComposer
1228
- : getGenericJSONScalar({
1229
- schemaComposer,
1230
- isInput: true,
1231
- subSchema,
1232
- validateWithJSONSchema,
1233
- });
1234
- }
1235
- return {
1236
- input: inputTypeComposer,
1237
- output: outputTypeComposer,
1238
- };
1239
- }
1240
- if (subSchema.anyOf && !subSchema.properties) {
1241
- if (subSchema.title === 'Any') {
1242
- const genericJSONScalar = getGenericJSONScalar({
1243
- schemaComposer,
1244
- isInput: false,
1245
- subSchema,
1246
- validateWithJSONSchema,
1247
- });
1248
- return {
1249
- input: genericJSONScalar,
1250
- output: genericJSONScalar,
1251
- };
1252
- }
1253
- // It should not have `required` because it is `anyOf` not `allOf`
1254
- const inputFieldMap = {};
1255
- const fieldMap = {};
1256
- let ableToUseGraphQLInputObjectType = true;
1257
- for (const typeComposers of subSchema.anyOf) {
1258
- const { input: inputTypeComposer, output: outputTypeComposer } = typeComposers;
1259
- if (inputTypeComposer instanceof graphqlCompose.ScalarTypeComposer) {
1260
- ableToUseGraphQLInputObjectType = false;
1261
- }
1262
- else {
1263
- const inputTypeElemFieldMap = inputTypeComposer.getFields();
1264
- for (const fieldName in inputTypeElemFieldMap) {
1265
- const field = inputTypeElemFieldMap[fieldName];
1266
- inputFieldMap[fieldName] = graphql.isNonNullType(field.type.getType())
1267
- ? {
1268
- ...field,
1269
- type: () => field.type.ofType,
1270
- }
1271
- : field;
1272
- }
1273
- }
1274
- if (outputTypeComposer instanceof graphqlCompose.ScalarTypeComposer) {
1275
- const typeName = outputTypeComposer.getTypeName();
1276
- fieldMap[typeName] = {
1277
- type: outputTypeComposer,
1278
- resolve: root => root,
1279
- };
1280
- }
1281
- else {
1282
- const typeElemFieldMap = outputTypeComposer.getFields();
1283
- for (const fieldName in typeElemFieldMap) {
1284
- const field = typeElemFieldMap[fieldName];
1285
- fieldMap[fieldName] = {
1286
- type: () => graphql.getNamedType(field.type.getType()),
1287
- ...field,
1288
- };
1289
- }
1290
- }
1291
- }
1292
- let inputTypeComposer;
1293
- const outputTypeComposer = schemaComposer.createObjectTC({
1294
- name: getValidTypeName({
1295
- schemaComposer,
1296
- isInput: false,
1297
- subSchema,
1298
- }),
1299
- description: subSchema.description,
1300
- fields: fieldMap,
1301
- extensions: {
1302
- validateWithJSONSchema,
1303
- examples: subSchema.examples,
1304
- default: subSchema.default,
1305
- },
1306
- });
1307
- if (ableToUseGraphQLInputObjectType) {
1308
- inputTypeComposer = schemaComposer.createInputTC({
1309
- name: getValidTypeName({
1310
- schemaComposer,
1311
- isInput: true,
1312
- subSchema,
1313
- }),
1314
- description: subSchema.description,
1315
- fields: inputFieldMap,
1316
- extensions: {
1317
- examples: subSchema.examples,
1318
- default: subSchema.default,
1319
- },
1320
- });
1321
- }
1322
- else {
1323
- inputTypeComposer = graphqlCompose.isSomeInputTypeComposer(outputTypeComposer)
1324
- ? outputTypeComposer
1325
- : getGenericJSONScalar({
1326
- schemaComposer,
1327
- isInput: true,
1328
- subSchema,
1329
- validateWithJSONSchema,
1330
- });
1331
- }
1332
- return {
1333
- input: inputTypeComposer,
1334
- output: outputTypeComposer,
1335
- };
1336
- }
1337
- if (Array.isArray(subSchema.type)) {
1338
- const validTypes = subSchema.type.filter((typeName) => typeName !== 'null');
1339
- if (validTypes.length === 1) {
1340
- subSchema.type = validTypes[0];
1341
- // continue with the single type
1342
- }
1343
- else {
1344
- const typeComposer = schemaComposer.getAnyTC(GraphQLVoid);
1345
- return {
1346
- input: typeComposer,
1347
- output: typeComposer,
1348
- };
1349
- }
1350
- }
1351
- switch (subSchema.type) {
1352
- case 'file': {
1353
- const typeComposer = schemaComposer.getAnyTC(GraphQLFile);
1354
- return {
1355
- input: typeComposer,
1356
- output: typeComposer,
1357
- description: subSchema.description,
1358
- };
1359
- }
1360
- case 'boolean': {
1361
- const typeComposer = schemaComposer.getAnyTC(graphql.GraphQLBoolean);
1362
- return {
1363
- input: typeComposer,
1364
- output: typeComposer,
1365
- description: subSchema.description,
1366
- };
1367
- }
1368
- case 'null': {
1369
- const typeComposer = schemaComposer.getAnyTC(GraphQLVoid);
1370
- return {
1371
- input: typeComposer,
1372
- output: typeComposer,
1373
- description: subSchema.description,
1374
- };
1375
- }
1376
- case 'integer': {
1377
- if (subSchema.format === 'int64') {
1378
- const typeComposer = schemaComposer.getAnyTC(graphqlScalars.GraphQLBigInt);
1379
- return {
1380
- input: typeComposer,
1381
- output: typeComposer,
1382
- description: subSchema.description,
1383
- };
1384
- }
1385
- const typeComposer = schemaComposer.getAnyTC(graphql.GraphQLInt);
1386
- return {
1387
- input: typeComposer,
1388
- output: typeComposer,
1389
- description: subSchema.description,
1390
- };
1391
- }
1392
- case 'number': {
1393
- const typeComposer = schemaComposer.getAnyTC(graphql.GraphQLFloat);
1394
- return {
1395
- input: typeComposer,
1396
- output: typeComposer,
1397
- description: subSchema.description,
1398
- };
1399
- }
1400
- case 'string': {
1401
- if (subSchema.minLength || subSchema.maxLength) {
1402
- const scalarType = getStringScalarWithMinMaxLength({
1403
- schemaComposer,
1404
- subSchema,
1405
- });
1406
- const typeComposer = schemaComposer.getAnyTC(scalarType);
1407
- return {
1408
- input: typeComposer,
1409
- output: typeComposer,
1410
- description: subSchema.description,
1411
- };
1412
- }
1413
- switch (subSchema.format) {
1414
- case 'date-time': {
1415
- const typeComposer = schemaComposer.getAnyTC(graphqlScalars.GraphQLDateTime);
1416
- return {
1417
- input: typeComposer,
1418
- output: typeComposer,
1419
- description: subSchema.description,
1420
- };
1421
- }
1422
- case 'time': {
1423
- const typeComposer = schemaComposer.getAnyTC(graphqlScalars.GraphQLTime);
1424
- return {
1425
- input: typeComposer,
1426
- output: typeComposer,
1427
- description: subSchema.description,
1428
- };
1429
- }
1430
- case 'email': {
1431
- const typeComposer = schemaComposer.getAnyTC(graphqlScalars.GraphQLEmailAddress);
1432
- return {
1433
- input: typeComposer,
1434
- output: typeComposer,
1435
- description: subSchema.description,
1436
- };
1437
- }
1438
- case 'ipv4': {
1439
- const typeComposer = schemaComposer.getAnyTC(graphqlScalars.GraphQLIPv4);
1440
- return {
1441
- input: typeComposer,
1442
- output: typeComposer,
1443
- description: subSchema.description,
1444
- };
1445
- }
1446
- case 'ipv6': {
1447
- const typeComposer = schemaComposer.getAnyTC(graphqlScalars.GraphQLIPv6);
1448
- return {
1449
- input: typeComposer,
1450
- output: typeComposer,
1451
- description: subSchema.description,
1452
- };
1453
- }
1454
- case 'uri': {
1455
- const typeComposer = schemaComposer.getAnyTC(graphqlScalars.GraphQLURL);
1456
- return {
1457
- input: typeComposer,
1458
- output: typeComposer,
1459
- description: subSchema.description,
1460
- };
1461
- }
1462
- default: {
1463
- const formatScalar = formatScalarMap.get(subSchema.format) || graphql.GraphQLString;
1464
- const typeComposer = schemaComposer.getAnyTC(formatScalar);
1465
- return {
1466
- input: typeComposer,
1467
- output: typeComposer,
1468
- description: subSchema.description,
1469
- };
1470
- }
1471
- }
1472
- }
1473
- case 'array':
1474
- if (typeof subSchema.items === 'object' &&
1475
- !Array.isArray(subSchema.items) &&
1476
- Object.keys(subSchema.items).length > 0) {
1477
- const typeComposers = subSchema.items;
1478
- return {
1479
- input: typeComposers.input.getTypePlural(),
1480
- output: typeComposers.output.getTypePlural(),
1481
- description: subSchema.description,
1482
- };
1483
- }
1484
- if (subSchema.contains) {
1485
- // Scalars cannot be in union type
1486
- const typeComposer = getGenericJSONScalar({
1487
- schemaComposer,
1488
- isInput: false,
1489
- subSchema,
1490
- validateWithJSONSchema,
1491
- }).getTypePlural();
1492
- return {
1493
- input: typeComposer,
1494
- output: typeComposer,
1495
- };
1496
- }
1497
- if (typeof subSchema.items === 'object' && Array.isArray(subSchema.items)) {
1498
- const existingItems = [...subSchema.items];
1499
- /* TODO
1500
- if (subSchema.additionalItems) {
1501
- existingItems.push(subSchema.additionalItems);
1502
- }
1503
- */
1504
- const { input: inputTypeComposer, output: outputTypeComposer } = getUnionTypeComposers({
1505
- schemaComposer,
1506
- ajv,
1507
- typeComposersList: existingItems,
1508
- subSchema,
1509
- generateInterfaceFromSharedFields,
1510
- });
1511
- return {
1512
- input: inputTypeComposer.getTypePlural(),
1513
- output: outputTypeComposer.getTypePlural(),
1514
- description: subSchema.description,
1515
- };
1516
- }
1517
- // If it doesn't have any clue
1518
- {
1519
- // const typeComposer = getGenericJSONScalar({
1520
- // schemaComposer,
1521
- // isInput: false,
1522
- // subSchema,
1523
- // validateWithJSONSchema,
1524
- // }).getTypePlural();
1525
- const typeComposer = schemaComposer.getAnyTC(graphqlScalars.GraphQLJSON).getTypePlural();
1526
- return {
1527
- input: typeComposer,
1528
- output: typeComposer,
1529
- description: subSchema.description,
1530
- };
1531
- }
1532
- case 'object':
1533
- const fieldMap = {};
1534
- let inputFieldMap = {};
1535
- if (subSchema.properties) {
1536
- subSchema.type = 'object';
1537
- for (const propertyName in subSchema.properties) {
1538
- // TODO: needs to be fixed
1539
- if (propertyName === 'additionalProperties') {
1540
- continue;
1541
- }
1542
- const typeComposers = subSchema.properties[propertyName];
1543
- const fieldName = utils.sanitizeNameForGraphQL(propertyName);
1544
- fieldMap[fieldName] = {
1545
- type: () => {
1546
- var _a;
1547
- return ((_a = subSchema.required) === null || _a === void 0 ? void 0 : _a.includes(propertyName))
1548
- ? typeComposers.output.getTypeNonNull()
1549
- : typeComposers.output;
1550
- },
1551
- // Make sure you get the right property
1552
- resolve: root => {
1553
- const actualFieldObj = root[propertyName];
1554
- if (actualFieldObj != null) {
1555
- const isArray = Array.isArray(actualFieldObj);
1556
- const isListType = isListTC(typeComposers.output);
1557
- if (isListType && !isArray) {
1558
- return [actualFieldObj];
1559
- }
1560
- else if (!isListTC(typeComposers.output) && isArray) {
1561
- return actualFieldObj[0];
1562
- }
1563
- }
1564
- return actualFieldObj;
1565
- },
1566
- description: typeComposers.description || ((_b = typeComposers.output) === null || _b === void 0 ? void 0 : _b.description),
1567
- };
1568
- inputFieldMap[fieldName] = {
1569
- type: () => {
1570
- var _a, _b;
1571
- return ((_a = subSchema.required) === null || _a === void 0 ? void 0 : _a.includes(propertyName))
1572
- ? (_b = typeComposers.input) === null || _b === void 0 ? void 0 : _b.getTypeNonNull()
1573
- : typeComposers.input;
1574
- },
1575
- // Let execution logic know what is the expected propertyName
1576
- extensions: {
1577
- propertyName,
1578
- },
1579
- description: typeComposers.description || ((_c = typeComposers.input) === null || _c === void 0 ? void 0 : _c.description),
1580
- defaultValue: ((_d = typeComposers === null || typeComposers === void 0 ? void 0 : typeComposers.extensions) === null || _d === void 0 ? void 0 : _d.default) || ((_e = typeComposers.input) === null || _e === void 0 ? void 0 : _e.default),
1581
- };
1582
- }
1583
- }
1584
- if (subSchema.allOf) {
1585
- for (const typeComposers of subSchema.allOf) {
1586
- const outputTC = typeComposers.output;
1587
- if (schemaComposer.isObjectType(outputTC)) {
1588
- for (const outputFieldName of outputTC.getFieldNames()) {
1589
- if (!fieldMap[outputFieldName]) {
1590
- fieldMap[outputFieldName] = outputTC.getField(outputFieldName);
1591
- }
1592
- }
1593
- }
1594
- const inputTC = typeComposers.input;
1595
- if (schemaComposer.isInputObjectType(inputTC)) {
1596
- for (const inputFieldName of inputTC.getFieldNames()) {
1597
- if (!inputFieldMap[inputFieldName]) {
1598
- inputFieldMap[inputFieldName] = inputTC.getField(inputFieldName);
1599
- }
1600
- }
1601
- }
1602
- }
1603
- }
1604
- if (subSchema.additionalProperties) {
1605
- if (typeof subSchema.additionalProperties === 'object' &&
1606
- subSchema.additionalProperties.output instanceof graphqlCompose.ObjectTypeComposer) {
1607
- if (Object.keys(fieldMap).length === 0) {
1608
- return subSchema.additionalProperties;
1609
- }
1610
- else {
1611
- const outputTC = subSchema.additionalProperties.output;
1612
- const outputTCFieldMap = outputTC.getFields();
1613
- for (const fieldName in outputTCFieldMap) {
1614
- fieldMap[fieldName] = outputTCFieldMap[fieldName];
1615
- }
1616
- const inputTC = subSchema.additionalProperties.input;
1617
- const inputTCFieldMap = inputTC.getFields();
1618
- for (const fieldName in inputTCFieldMap) {
1619
- inputFieldMap[fieldName] = inputTCFieldMap[fieldName];
1620
- }
1621
- }
1622
- }
1623
- else {
1624
- fieldMap.additionalProperties = {
1625
- type: graphqlScalars.GraphQLJSON,
1626
- resolve: (root) => root,
1627
- };
1628
- inputFieldMap = {};
1629
- }
1630
- }
1631
- if (subSchema.title === '_schema') {
1632
- futureTasks.forEach(futureTask => futureTask());
1633
- return {
1634
- output: schemaComposer,
1635
- };
1636
- }
1637
- if (subSchema.title === 'Query') {
1638
- const typeComposer = schemaComposer.Query;
1639
- typeComposer.addFields(fieldMap);
1640
- return {
1641
- output: typeComposer,
1642
- };
1643
- }
1644
- if (subSchema.title === 'Mutation') {
1645
- const typeComposer = schemaComposer.Mutation;
1646
- typeComposer.addFields(fieldMap);
1647
- return {
1648
- output: typeComposer,
1649
- };
1650
- }
1651
- if (subSchema.title === 'Subscription') {
1652
- const typeComposer = schemaComposer.Subscription;
1653
- typeComposer.addFields(fieldMap);
1654
- return {
1655
- output: typeComposer,
1656
- };
1657
- }
1658
- const getCorrectInputFieldType = (fieldName) => {
1659
- const inputType = inputFieldMap[fieldName].type();
1660
- const actualInputType = isListTC(inputType) ? inputType.ofType : inputType;
1661
- if (!actualInputType.getFields) {
1662
- return actualInputType;
1663
- }
1664
- const fieldMap = actualInputType.getFields();
1665
- for (const fieldName in fieldMap) {
1666
- const fieldConfig = fieldMap[fieldName];
1667
- if (fieldConfig.type.getTypeName().endsWith('!')) {
1668
- return inputType.getTypeNonNull();
1669
- }
1670
- }
1671
- return inputType;
1672
- };
1673
- if (subSchema.title === 'QueryInput') {
1674
- const typeComposer = schemaComposer.Query;
1675
- for (const fieldName in inputFieldMap) {
1676
- futureTasks.add(() => typeComposer.addFieldArgs(fieldName, {
1677
- input: {
1678
- type: () => getCorrectInputFieldType(fieldName),
1679
- description: inputFieldMap[fieldName].description,
1680
- },
1681
- }));
1682
- }
1683
- return {
1684
- output: typeComposer,
1685
- };
1686
- }
1687
- if (subSchema.title === 'MutationInput') {
1688
- const typeComposer = schemaComposer.Mutation;
1689
- for (const fieldName in inputFieldMap) {
1690
- futureTasks.add(() => typeComposer.addFieldArgs(fieldName, {
1691
- input: {
1692
- type: () => getCorrectInputFieldType(fieldName),
1693
- description: inputFieldMap[fieldName].description,
1694
- },
1695
- }));
1696
- }
1697
- return {
1698
- output: typeComposer,
1699
- };
1700
- }
1701
- if (subSchema.title === 'SubscriptionInput') {
1702
- const typeComposer = schemaComposer.Subscription;
1703
- for (const fieldName in inputFieldMap) {
1704
- futureTasks.add(() => typeComposer.addFieldArgs(fieldName, {
1705
- input: {
1706
- type: () => getCorrectInputFieldType(fieldName),
1707
- description: inputFieldMap[fieldName].description,
1708
- },
1709
- }));
1710
- }
1711
- return {
1712
- output: typeComposer,
1713
- };
1714
- }
1715
- const output = Object.keys(fieldMap).length === 0
1716
- ? getGenericJSONScalar({
1717
- schemaComposer,
1718
- isInput: false,
1719
- subSchema,
1720
- validateWithJSONSchema,
1721
- })
1722
- : schemaComposer.createObjectTC({
1723
- name: getValidTypeName({
1724
- schemaComposer,
1725
- isInput: false,
1726
- subSchema,
1727
- }),
1728
- description: subSchema.description,
1729
- fields: fieldMap,
1730
- extensions: {
1731
- validateWithJSONSchema,
1732
- examples: subSchema.examples,
1733
- default: subSchema.default,
1734
- },
1735
- });
1736
- const input = Object.keys(inputFieldMap).length === 0
1737
- ? getGenericJSONScalar({
1738
- schemaComposer,
1739
- isInput: true,
1740
- subSchema,
1741
- validateWithJSONSchema,
1742
- })
1743
- : schemaComposer.createInputTC({
1744
- name: getValidTypeName({
1745
- schemaComposer,
1746
- isInput: true,
1747
- subSchema,
1748
- }),
1749
- description: subSchema.description,
1750
- fields: inputFieldMap,
1751
- extensions: {
1752
- examples: subSchema.examples,
1753
- default: subSchema.default,
1754
- },
1755
- });
1756
- return {
1757
- input,
1758
- output,
1759
- };
1760
- }
1761
- logger.warn(`GraphQL Type cannot be created for this JSON Schema definition;`, {
1762
- subSchema,
1763
- path,
1764
- });
1765
- const typeComposer = schemaComposer.getAnyTC(graphqlScalars.GraphQLJSON);
1766
- return {
1767
- input: typeComposer,
1768
- output: typeComposer,
1769
- };
1770
- };
1771
- const result = getTypeComposer();
1772
- return result;
1773
- });
1774
- }
1775
-
1776
- async function getGraphQLSchemaFromDereferencedJSONSchema(fullyDeferencedSchema, { fetch, logger, operations, operationHeaders, baseUrl, pubsub, generateInterfaceFromSharedFields, queryParams, queryStringOptions, }) {
1777
- logger.debug(`Generating GraphQL Schema from the bundled JSON Schema`);
1778
- const visitorResult = await getComposerFromJSONSchema(fullyDeferencedSchema, logger, generateInterfaceFromSharedFields);
1779
- const schemaComposerWithoutExecutionLogic = visitorResult.output;
1780
- if (!(schemaComposerWithoutExecutionLogic instanceof graphqlCompose.SchemaComposer)) {
1781
- throw new Error('The visitor result should be a SchemaComposer instance.');
1782
- }
1783
- // graphql-compose doesn't add @defer and @stream to the schema
1784
- for (const directive of graphql.specifiedDirectives) {
1785
- schemaComposerWithoutExecutionLogic.addDirective(directive);
1786
- }
1787
- const schemaComposerWithExecutionLogic = await addExecutionLogicToComposer(schemaComposerWithoutExecutionLogic, {
1788
- fetch,
1789
- logger,
1790
- operations,
1791
- operationHeaders,
1792
- baseUrl,
1793
- pubsub,
1794
- queryParams,
1795
- queryStringOptions,
1796
- });
1797
- if (schemaComposerWithExecutionLogic.Query.getFieldNames().length === 0) {
1798
- schemaComposerWithExecutionLogic.Query.addFields({
1799
- dummy: {
1800
- type: 'String',
1801
- resolve: () => 'dummy',
1802
- },
1803
- });
1804
- }
1805
- return schemaComposerWithExecutionLogic.buildSchema();
1806
- }
1807
-
1808
- async function loadGraphQLSchemaFromJSONSchemas(name, options) {
1809
- const logger = options.logger || new utils.DefaultLogger(name);
1810
- const operations = options.operations;
1811
- const cwd = options.cwd || process.cwd();
1812
- const fullyDeferencedSchema = await getDereferencedJSONSchemaFromOperations({
1813
- operations,
1814
- cwd,
1815
- logger,
1816
- fetchFn: options.fetch,
1817
- schemaHeaders: options.schemaHeaders,
1818
- ignoreErrorResponses: options.ignoreErrorResponses,
1819
- noDeduplication: options.noDeduplication,
1820
- });
1821
- const graphqlSchema = await getGraphQLSchemaFromDereferencedJSONSchema(fullyDeferencedSchema, {
1822
- fetch: options.fetch,
1823
- logger,
1824
- operations,
1825
- operationHeaders: options.operationHeaders,
1826
- baseUrl: options.baseUrl,
1827
- pubsub: options.pubsub,
1828
- generateInterfaceFromSharedFields: options.generateInterfaceFromSharedFields,
1829
- queryParams: options.queryParams,
1830
- queryStringOptions: options.queryStringOptions,
1831
- });
1832
- return graphqlSchema;
1833
- }
1834
-
1835
- async function createBundle(name, { baseUrl, operations, schemaHeaders, operationHeaders, cwd = process.cwd(), fetch: fetch$1 = fetch.fetch, logger = new utils.DefaultLogger(name), ignoreErrorResponses = false, noDeduplication = false, }) {
1836
- logger.debug(`Creating the dereferenced schema from operations config`);
1837
- const dereferencedSchema = await getDereferencedJSONSchemaFromOperations({
1838
- operations,
1839
- cwd,
1840
- logger,
1841
- fetchFn: fetch$1,
1842
- schemaHeaders,
1843
- ignoreErrorResponses,
1844
- noDeduplication,
1845
- });
1846
- logger.debug(`Creating references from dereferenced schema`);
1847
- const referencedSchema = await jsonMachete.referenceJSONSchema(dereferencedSchema);
1848
- logger.debug(`Bundle generation finished`);
1849
- return {
1850
- name,
1851
- baseUrl,
1852
- operations,
1853
- operationHeaders,
1854
- referencedSchema,
1855
- };
1856
- }
1857
- /**
1858
- * Generates a local GraphQLSchema instance from
1859
- * previously generated JSON Schema bundle
1860
- */
1861
- async function getGraphQLSchemaFromBundle({ name, baseUrl: bundledBaseUrl, operations, operationHeaders: bundledOperationHeaders = {}, referencedSchema, }, { cwd = process.cwd(), fetch: fetch$1 = fetch.fetch, pubsub, logger = new utils.DefaultLogger(name), baseUrl: overwrittenBaseUrl, operationHeaders: additionalOperationHeaders = {}, queryParams, queryStringOptions, } = {}) {
1862
- logger.info(`Dereferencing the bundle`);
1863
- const fullyDeferencedSchema = await jsonMachete.dereferenceObject(referencedSchema, {
1864
- cwd,
1865
- fetchFn: fetch$1,
1866
- logger,
1867
- });
1868
- const operationHeaders = { ...bundledOperationHeaders, ...additionalOperationHeaders };
1869
- logger.info(`Creating the GraphQL Schema from dereferenced schema`);
1870
- return getGraphQLSchemaFromDereferencedJSONSchema(fullyDeferencedSchema, {
1871
- fetch: fetch$1,
1872
- pubsub,
1873
- logger,
1874
- baseUrl: overwrittenBaseUrl || bundledBaseUrl,
1875
- operations,
1876
- operationHeaders,
1877
- queryParams,
1878
- queryStringOptions,
1879
- });
1880
- }
1881
-
1882
- exports.anySchema = anySchema;
1883
- exports.createBundle = createBundle;
1884
- exports.default = loadGraphQLSchemaFromJSONSchemas;
1885
- exports.getComposerFromJSONSchema = getComposerFromJSONSchema;
1886
- exports.getDereferencedJSONSchemaFromOperations = getDereferencedJSONSchemaFromOperations;
1887
- exports.getGraphQLSchemaFromBundle = getGraphQLSchemaFromBundle;
1888
- exports.getGraphQLSchemaFromDereferencedJSONSchema = getGraphQLSchemaFromDereferencedJSONSchema;
1889
- exports.getReferencedJSONSchemaFromOperations = getReferencedJSONSchemaFromOperations;
1890
- exports.loadGraphQLSchemaFromJSONSchemas = loadGraphQLSchemaFromJSONSchemas;