-
Notifications
You must be signed in to change notification settings - Fork 206
/
preprocessor.ts
1691 lines (1520 loc) · 52.6 KB
/
preprocessor.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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: openapi-to-graphql
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
// Type imports:
import {
Oas3,
CallbackObject,
LinkObject,
OperationObject,
ReferenceObject,
SchemaObject,
PathItemObject
} from './types/oas3'
import { InternalOptions } from './types/options'
import { Operation, DataDefinition } from './types/operation'
import {
PreprocessingData,
ProcessedSecurityScheme
} from './types/preprocessing_data'
// Imports:
import * as Oas3Tools from './oas_3_tools'
import * as deepEqual from 'deep-equal'
import debug from 'debug'
import { handleWarning, getCommonPropertyNames, MitigationTypes } from './utils'
import { GraphQLOperationType } from './types/graphql'
import { methodToHttpMethod } from './oas_3_tools'
const preprocessingLog = debug('preprocessing')
/**
* Given an operation object from the OAS, create an Operation, which contains
* the necessary data to create a GraphQL wrapper for said operation object.
*
* @param path The path of the operation object
* @param method The method of the operation object
* @param operationString A string representation of the path and the method (and the OAS title if applicable)
* @param operationType Whether the operation should be turned into a Query/Mutation/Subscription operation
* @param operation The operation object from the OAS
* @param pathItem The path item object from the OAS from which the operation object is derived from
* @param oas The OAS from which the path item and operation object are derived from
* @param data An assortment of data which at this point is mainly used enable logging
* @param options The options passed by the user
*/
function processOperation<TSource, TContext, TArgs>(
path: string,
method: Oas3Tools.HTTP_METHODS,
operationString: string,
operationType: GraphQLOperationType,
operation: OperationObject,
pathItem: PathItemObject,
oas: Oas3,
data: PreprocessingData<TSource, TContext, TArgs>,
options: InternalOptions<TSource, TContext, TArgs>
): Operation {
// Determine description
let description = operation.description
if (
(typeof description !== 'string' || description === '') &&
typeof operation.summary === 'string'
) {
description = operation.summary
}
if (data.options.equivalentToMessages) {
// Description may not exist
if (typeof description !== 'string') {
description = ''
}
description += `\n\nEquivalent to ${operationString}`
}
// Determine tags
const tags = operation.tags || []
// Hold on to the operationId
const operationId =
typeof operation.operationId !== 'undefined'
? operation.operationId
: Oas3Tools.generateOperationId(method, path)
// Request schema
const {
payloadContentType,
payloadSchema,
payloadSchemaNames,
payloadRequired
} = Oas3Tools.getRequestSchemaAndNames(path, method, operation, oas)
const payloadDefinition =
payloadSchema && typeof payloadSchema !== 'undefined'
? createDataDef(
payloadSchemaNames,
payloadSchema as SchemaObject,
true,
data,
oas
)
: undefined
// Response schema
const {
responseContentType,
responseSchema,
responseSchemaNames,
statusCode
} = Oas3Tools.getResponseSchemaAndNames(
path,
method,
operation,
oas,
data,
options
)
if (!responseSchema || typeof responseSchema !== 'object') {
handleWarning({
mitigationType: MitigationTypes.MISSING_RESPONSE_SCHEMA,
message:
`Operation ${operationString} has no (valid) response schema. ` +
`You can use the fillEmptyResponses option to create a ` +
`placeholder schema`,
data,
log: preprocessingLog
})
return undefined
}
// Links
const links = Oas3Tools.getLinks(path, method, operation, oas, data)
const responseDefinition = createDataDef(
responseSchemaNames,
responseSchema as SchemaObject,
false,
data,
oas,
links
)
// Parameters
const parameters = Oas3Tools.getParameters(
path,
method,
operation,
pathItem,
oas
)
// Security protocols
const securityRequirements = options.viewer
? Oas3Tools.getSecurityRequirements(operation, data.security, oas)
: []
// Servers
const servers = Oas3Tools.getServers(operation, pathItem, oas)
// Whether to place this operation into an authentication viewer
const inViewer =
securityRequirements.length > 0 && data.options.viewer !== false
return {
operation,
operationId,
operationString,
operationType,
description,
tags,
path,
method,
payloadContentType,
payloadDefinition,
payloadRequired,
responseContentType,
responseDefinition,
parameters,
securityRequirements,
servers,
inViewer,
statusCode,
oas
}
}
/**
* Extract information from the OAS and put it inside a data structure that
* is easier for OpenAPI-to-GraphQL to use
*/
export function preprocessOas<TSource, TContext, TArgs>(
oass: Oas3[],
options: InternalOptions<TSource, TContext, TArgs>
): PreprocessingData<TSource, TContext, TArgs> {
const data: PreprocessingData<TSource, TContext, TArgs> = {
operations: {},
callbackOperations: {},
usedTypeNames: [
'Query', // Used by OpenAPI-to-GraphQL for root-level element
'Mutation', // Used by OpenAPI-to-GraphQL for root-level element
'Subscription' // Used by OpenAPI-to-GraphQL for root-level element
],
defs: [],
security: {},
saneMap: {},
options,
oass
}
oass.forEach((oas) => {
// Store stats on OAS:
data.options.report.numOps += Oas3Tools.countOperations(oas)
data.options.report.numOpsMutation += Oas3Tools.countOperationsMutation(oas)
data.options.report.numOpsQuery += Oas3Tools.countOperationsQuery(oas)
if (data.options.createSubscriptionsFromCallbacks) {
data.options.report.numOpsSubscription += Oas3Tools.countOperationsSubscription(
oas
)
} else {
data.options.report.numOpsSubscription = 0
}
// Get security schemes
const currentSecurity = getProcessedSecuritySchemes(oas, data)
const commonSecurityPropertyName = getCommonPropertyNames(
data.security,
currentSecurity
)
commonSecurityPropertyName.forEach((propertyName) => {
handleWarning({
mitigationType: MitigationTypes.DUPLICATE_SECURITY_SCHEME,
message: `Multiple OASs share security schemes with the same name '${propertyName}'`,
mitigationAddendum:
`The security scheme from OAS ` +
`'${currentSecurity[propertyName].oas.info.title}' will be ignored`,
data,
log: preprocessingLog
})
})
// Do not overwrite preexisting security schemes
data.security = { ...currentSecurity, ...data.security }
// Process all operations
for (let path in oas.paths) {
const pathItem = !('$ref' in oas.paths[path])
? oas.paths[path]
: (Oas3Tools.resolveRef(oas.paths[path]['$ref'], oas) as PathItemObject)
Object.keys(pathItem)
.filter((objectKey) => {
/**
* Get only fields that contain operation objects
*
* Can also contain other fields such as summary or description
*/
return Oas3Tools.isHttpMethod(objectKey)
})
.forEach((rawMethod) => {
const operationString =
oass.length === 1
? Oas3Tools.formatOperationString(rawMethod, path)
: Oas3Tools.formatOperationString(rawMethod, path, oas.info.title)
let httpMethod: Oas3Tools.HTTP_METHODS
try {
httpMethod = methodToHttpMethod(rawMethod)
} catch (e) {
handleWarning({
mitigationType: MitigationTypes.INVALID_HTTP_METHOD,
message: `Invalid HTTP method '${rawMethod}' in operation '${operationString}'`,
data,
log: preprocessingLog
})
return
}
const operation = pathItem[httpMethod] as OperationObject
let operationType =
httpMethod === Oas3Tools.HTTP_METHODS.get
? GraphQLOperationType.Query
: GraphQLOperationType.Mutation
// Option selectQueryOrMutationField can override operation type
if (
typeof options.selectQueryOrMutationField === 'object' &&
typeof options.selectQueryOrMutationField[oas.info.title] ===
'object' &&
typeof options.selectQueryOrMutationField[oas.info.title][path] ===
'object' &&
typeof options.selectQueryOrMutationField[oas.info.title][path][
httpMethod
] === 'number' // This is an TS enum, which is translated to have a integer value
) {
operationType =
options.selectQueryOrMutationField[oas.info.title][path][
httpMethod
] === GraphQLOperationType.Mutation
? GraphQLOperationType.Mutation
: GraphQLOperationType.Query
}
const operationData = processOperation(
path,
httpMethod,
operationString,
operationType,
operation,
pathItem,
oas,
data,
options
)
if (operationData) {
/**
* Handle operationId property name collision
* May occur if multiple OAS are provided
*/
if (
operationData &&
!(operationData.operationId in data.operations)
) {
data.operations[operationData.operationId] = operationData
} else {
handleWarning({
mitigationType: MitigationTypes.DUPLICATE_OPERATIONID,
message: `Multiple OASs share operations with the same operationId '${operationData.operationId}'`,
mitigationAddendum: `The operation from the OAS '${operationData.oas.info.title}' will be ignored`,
data,
log: preprocessingLog
})
}
}
// Process all callbacks
if (
data.options.createSubscriptionsFromCallbacks &&
operation.callbacks
) {
Object.entries(operation.callbacks).forEach(
([callbackName, callback]) => {
const resolvedCallback = !('$ref' in callback)
? callback
: (Oas3Tools.resolveRef(
(callback as ReferenceObject)['$ref'],
oas
) as CallbackObject)
Object.entries(resolvedCallback).forEach(
([callbackExpression, callbackPathItem]) => {
const resolvedCallbackPathItem = !(
'$ref' in callbackPathItem
)
? callbackPathItem
: Oas3Tools.resolveRef(callbackPathItem['$ref'], oas)
const callbackOperationObjectMethods = Object.keys(
resolvedCallbackPathItem
).filter((objectKey) => {
/**
* Get only fields that contain operation objects
*
* Can also contain other fields such as summary or description
*/
return Oas3Tools.isHttpMethod(objectKey)
})
if (callbackOperationObjectMethods.length > 0) {
if (callbackOperationObjectMethods.length > 1) {
handleWarning({
mitigationType:
MitigationTypes.CALLBACKS_MULTIPLE_OPERATION_OBJECTS,
message: `Callback '${callbackExpression}' on operation '${operationString}' has multiple operation objects with the methods '${callbackOperationObjectMethods}'. OpenAPI-to-GraphQL can only utilize one of these operation objects.`,
mitigationAddendum: `The operation with the method '${callbackOperationObjectMethods[0]}' will be selected and all others will be ignored.`,
data,
log: preprocessingLog
})
}
// Select only one of the operation object methods
const callbackRawMethod =
callbackOperationObjectMethods[0]
const callbackOperationString =
oass.length === 1
? Oas3Tools.formatOperationString(
httpMethod,
callbackName
)
: Oas3Tools.formatOperationString(
httpMethod,
callbackName,
oas.info.title
)
let callbackHttpMethod: Oas3Tools.HTTP_METHODS
try {
callbackHttpMethod = methodToHttpMethod(
callbackRawMethod
)
} catch (e) {
handleWarning({
mitigationType: MitigationTypes.INVALID_HTTP_METHOD,
message: `Invalid HTTP method '${rawMethod}' in callback '${callbackOperationString}' in operation '${operationString}'`,
data,
log: preprocessingLog
})
return
}
const callbackOperation = processOperation(
callbackExpression,
callbackHttpMethod,
callbackOperationString,
GraphQLOperationType.Subscription,
resolvedCallbackPathItem[callbackHttpMethod],
callbackPathItem,
oas,
data,
options
)
if (callbackOperation) {
/**
* Handle operationId property name collision
* May occur if multiple OAS are provided
*/
if (
callbackOperation &&
!(
callbackOperation.operationId in
data.callbackOperations
)
) {
data.callbackOperations[
callbackOperation.operationId
] = callbackOperation
} else {
handleWarning({
mitigationType:
MitigationTypes.DUPLICATE_OPERATIONID,
message: `Multiple OASs share callback operations with the same operationId '${callbackOperation.operationId}'`,
mitigationAddendum: `The callback operation from the OAS '${operationData.oas.info.title}' will be ignored`,
data,
log: preprocessingLog
})
}
}
}
}
)
}
)
}
})
}
})
return data
}
/**
* Extracts the security schemes from given OAS and organizes the information in
* a data structure that is easier for OpenAPI-to-GraphQL to use
*
* Here is the structure of the data:
* {
* {string} [sanitized name] { Contains information about the security protocol
* {string} rawName Stores the raw security protocol name
* {object} def Definition provided by OAS
* {object} parameters Stores the names of the authentication credentials
* NOTE: Structure will depend on the type of the protocol
* (e.g. basic authentication, API key, etc.)
* NOTE: Mainly used for the AnyAuth viewers
* {object} schema Stores the GraphQL schema to create the viewers
* }
* }
*
* Here is an example:
* {
* MyApiKey: {
* rawName: "My_api_key",
* def: { ... },
* parameters: {
* apiKey: MyKeyApiKey
* },
* schema: { ... }
* }
* MyBasicAuth: {
* rawName: "My_basic_auth",
* def: { ... },
* parameters: {
* username: MyBasicAuthUsername,
* password: MyBasicAuthPassword,
* },
* schema: { ... }
* }
* }
*/
function getProcessedSecuritySchemes<TSource, TContext, TArgs>(
oas: Oas3,
data: PreprocessingData<TSource, TContext, TArgs>
): { [key: string]: ProcessedSecurityScheme } {
const result = {}
const security = Oas3Tools.getSecuritySchemes(oas)
// Loop through all the security protocols
for (let schemeKey in security) {
const securityScheme = security[schemeKey]
// Determine the schema and the parameters for the security protocol
let schema
let parameters = {}
let description
switch (securityScheme.type) {
case 'apiKey':
description = `API key credentials for the security protocol '${schemeKey}'`
if (data.oass.length > 1) {
description += ` in ${oas.info.title}`
}
parameters = {
apiKey: Oas3Tools.sanitize(
`${schemeKey}_apiKey`,
Oas3Tools.CaseStyle.camelCase
)
}
schema = {
type: 'object',
description,
properties: {
apiKey: {
type: 'string'
}
}
}
break
case 'http':
switch (securityScheme.scheme) {
/**
* TODO: HTTP has a number of authentication types
*
* See http://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml
*/
case 'basic':
description = `Basic auth credentials for security protocol '${schemeKey}'`
parameters = {
username: Oas3Tools.sanitize(
`${schemeKey}_username`,
Oas3Tools.CaseStyle.camelCase
),
password: Oas3Tools.sanitize(
`${schemeKey}_password`,
Oas3Tools.CaseStyle.camelCase
)
}
schema = {
type: 'object',
description,
properties: {
username: {
type: 'string'
},
password: {
type: 'string'
}
}
}
break
default:
handleWarning({
mitigationType: MitigationTypes.UNSUPPORTED_HTTP_SECURITY_SCHEME,
message:
`Currently unsupported HTTP authentication protocol ` +
`type 'http' and scheme '${securityScheme.scheme}' in OAS ` +
`'${oas.info.title}'`,
data,
log: preprocessingLog
})
}
break
// TODO: Implement
case 'openIdConnect':
handleWarning({
mitigationType: MitigationTypes.UNSUPPORTED_HTTP_SECURITY_SCHEME,
message:
`Currently unsupported HTTP authentication protocol ` +
`type 'openIdConnect' in OAS '${oas.info.title}'`,
data,
log: preprocessingLog
})
break
case 'oauth2':
handleWarning({
mitigationType: MitigationTypes.OAUTH_SECURITY_SCHEME,
message:
`OAuth security scheme found in OAS '${oas.info.title}'. ` +
`OAuth support is provided using the 'tokenJSONpath' option`,
data,
log: preprocessingLog
})
// Continue because we do not want to create an OAuth viewer
continue
default:
handleWarning({
mitigationType: MitigationTypes.UNSUPPORTED_HTTP_SECURITY_SCHEME,
message:
`Unsupported HTTP authentication protocol` +
`type '${securityScheme.type}' in OAS '${oas.info.title}'`,
data,
log: preprocessingLog
})
}
// Add protocol data to the output
result[schemeKey] = {
rawName: schemeKey,
def: securityScheme,
parameters,
schema,
oas
}
}
return result
}
/**
* Method to either create a new or reuse an existing, centrally stored data
* definition.
*/
export function createDataDef<TSource, TContext, TArgs>(
names: Oas3Tools.SchemaNames,
schema: SchemaObject,
isInputObjectType: boolean,
data: PreprocessingData<TSource, TContext, TArgs>,
oas: Oas3,
links?: { [key: string]: LinkObject }
): DataDefinition {
const preferredName = getPreferredName(names)
// Basic validation test
if (typeof schema !== 'object') {
handleWarning({
mitigationType: MitigationTypes.MISSING_SCHEMA,
message:
`Could not create data definition for schema with ` +
`preferred name '${preferredName}' and schema '${JSON.stringify(
schema
)}'`,
data,
log: preprocessingLog
})
// TODO: Does this change make the option fillEmptyResponses obsolete?
return {
preferredName,
schema: null,
required: [],
links: null,
subDefinitions: null,
graphQLTypeName: null,
graphQLInputObjectTypeName: null,
targetGraphQLType: 'json'
}
} else {
if ('$ref' in schema) {
schema = Oas3Tools.resolveRef(schema['$ref'], oas)
}
const saneLinks = {}
if (typeof links === 'object') {
Object.keys(links).forEach((linkKey) => {
saneLinks[
Oas3Tools.sanitize(
linkKey,
!data.options.simpleNames
? Oas3Tools.CaseStyle.camelCase
: Oas3Tools.CaseStyle.simple
)
] = links[linkKey]
})
}
// Determine the index of possible existing data definition
const index = getSchemaIndex(preferredName, schema, data.defs)
if (index !== -1) {
// Found existing data definition and fetch it
const existingDataDef = data.defs[index]
/**
* Collapse links if possible, i.e. if the current operation has links,
* combine them with the prexisting ones
*/
if (typeof saneLinks !== 'undefined') {
if (typeof existingDataDef.links !== 'undefined') {
// Check if there are any overlapping links
Object.keys(existingDataDef.links).forEach((saneLinkKey) => {
if (
typeof saneLinks[saneLinkKey] !== 'undefined' &&
!deepEqual(
existingDataDef.links[saneLinkKey],
saneLinks[saneLinkKey]
)
) {
handleWarning({
mitigationType: MitigationTypes.DUPLICATE_LINK_KEY,
message:
`Multiple operations with the same response body share the same sanitized ` +
`link key '${saneLinkKey}' but have different link definitions ` +
`'${JSON.stringify(
existingDataDef.links[saneLinkKey]
)}' and ` +
`'${JSON.stringify(saneLinks[saneLinkKey])}'.`,
data,
log: preprocessingLog
})
}
})
/**
* Collapse the links
*
* Avoid overwriting preexisting links
*/
existingDataDef.links = { ...saneLinks, ...existingDataDef.links }
} else {
// No preexisting links, so simply assign the links
existingDataDef.links = saneLinks
}
}
return existingDataDef
} else {
// Else, define a new name, store the def, and return it
const name = getSchemaName(names, data.usedTypeNames)
// Store and sanitize the name
const saneName = !data.options.simpleNames
? Oas3Tools.sanitize(name, Oas3Tools.CaseStyle.PascalCase)
: Oas3Tools.capitalize(
Oas3Tools.sanitize(name, Oas3Tools.CaseStyle.simple)
)
const saneInputName = Oas3Tools.capitalize(saneName + 'Input')
Oas3Tools.storeSaneName(saneName, name, data.saneMap)
/**
* TODO: is there a better way of copying the schema object?
*
* Perhaps, just copy it at the root level (operation schema)
*/
const collapsedSchema = resolveAllOf(schema, {}, data, oas)
const targetGraphQLType = Oas3Tools.getSchemaTargetGraphQLType(
collapsedSchema as SchemaObject,
data
)
const def: DataDefinition = {
preferredName,
/**
* Note that schema may contain $ref or schema composition (e.g. allOf)
*
* TODO: the schema is used in getSchemaIndex, which allows us to check
* whether a dataDef has already been created for that particular
* schema and name pair. The look up should resolve references but
* currently, it does not.
*/
schema,
required: [],
targetGraphQLType,
subDefinitions: undefined,
links: saneLinks,
graphQLTypeName: saneName,
graphQLInputObjectTypeName: saneInputName
}
// Used type names and defs of union and object types are pushed during creation
if (
targetGraphQLType === 'object' ||
targetGraphQLType === 'list' ||
targetGraphQLType === 'enum'
) {
data.usedTypeNames.push(saneName)
data.usedTypeNames.push(saneInputName)
// Add the def to the master list
data.defs.push(def)
}
// We currently only support simple cases of anyOf and oneOf
if (
// TODO: Should also consider if the member schema contains type data
(Array.isArray(collapsedSchema.anyOf) &&
Array.isArray(collapsedSchema.oneOf)) || // anyOf and oneOf used concurrently
hasNestedAnyOfUsage(collapsedSchema, oas) ||
hasNestedOneOfUsage(collapsedSchema, oas)
) {
handleWarning({
mitigationType: MitigationTypes.COMBINE_SCHEMAS,
message:
`Schema '${JSON.stringify(schema)}' contains either both ` +
`'anyOf' and 'oneOf' or nested 'anyOf' and 'oneOf' which ` +
`is currently not supported.`,
mitigationAddendum: `Use arbitrary JSON type instead.`,
data,
log: preprocessingLog
})
def.targetGraphQLType = 'json'
return def
}
// oneOf will ideally be turned into a union type
if (Array.isArray(collapsedSchema.oneOf)) {
const oneOfDataDef = createDataDefFromOneOf(
saneName,
saneInputName,
collapsedSchema,
isInputObjectType,
def,
data,
oas
)
if (typeof oneOfDataDef === 'object') {
return oneOfDataDef
}
}
/**
* anyOf will ideally be turned into an object type
*
* Fields common to all member schemas will be made non-null
*/
if (Array.isArray(collapsedSchema.anyOf)) {
const anyOfDataDef = createDataDefFromAnyOf(
saneName,
saneInputName,
collapsedSchema,
isInputObjectType,
def,
data,
oas
)
if (typeof anyOfDataDef === 'object') {
return anyOfDataDef
}
}
if (targetGraphQLType) {
switch (targetGraphQLType) {
case 'list':
if (typeof collapsedSchema.items === 'object') {
// Break schema down into component parts
// I.e. if it is an list type, create a reference to the list item type
// Or if it is an object type, create references to all of the field types
let itemsSchema = collapsedSchema.items
let itemsName = `${name}ListItem`
if ('$ref' in itemsSchema) {
itemsName = collapsedSchema.items['$ref'].split('/').pop()
}
const subDefinition = createDataDef(
// Is this the correct classification for this name? It does not matter in the long run.
{ fromRef: itemsName },
itemsSchema as SchemaObject,
isInputObjectType,
data,
oas
)
// Add list item reference
def.subDefinitions = subDefinition
}
break
case 'object':
def.subDefinitions = {}
if (
typeof collapsedSchema.properties === 'object' &&
Object.keys(collapsedSchema.properties).length > 0
) {
addObjectPropertiesToDataDef(
def,
collapsedSchema,
def.required,
isInputObjectType,
data,
oas
)
} else {
handleWarning({
mitigationType: MitigationTypes.OBJECT_MISSING_PROPERTIES,
message:
`Schema ${JSON.stringify(schema)} does not have ` +
`any properties`,
data,
log: preprocessingLog
})
def.targetGraphQLType = 'json'
}
break
}
} else {
// No target GraphQL type
handleWarning({
mitigationType: MitigationTypes.UNKNOWN_TARGET_TYPE,
message: `No GraphQL target type could be identified for schema '${JSON.stringify(
schema
)}'.`,
data,
log: preprocessingLog
})
def.targetGraphQLType = 'json'
}
return def
}
}
}
/**
* Returns the index of the data definition object in the given list that
* contains the same schema and preferred name as the given one. Returns -1 if
* that schema could not be found.
*/
function getSchemaIndex(
preferredName: string,
schema: SchemaObject,
dataDefs: DataDefinition[]
): number {
/**
* TODO: instead of iterating through the whole list every time, create a
* hashing function and store all of the DataDefinitions in a hashmap.
*/
for (let index = 0; index < dataDefs.length; index++) {
const def = dataDefs[index]
/**
* TODO: deepEquals is not sufficient. We also need to resolve references.
* However, deepEquals should work for vast majority of cases.
*/
if (preferredName === def.preferredName && deepEqual(schema, def.schema)) {
return index
}
}
// The schema could not be found in the master list
return -1
}
/**
* Determines the preferred name to use for schema regardless of name collisions.
*
* In other words, determines the ideal name for a schema.
*
* Similar to getSchemaName() except it does not check if the name has already
* been taken.
*/
function getPreferredName(names: Oas3Tools.SchemaNames): string {
if (typeof names.preferred === 'string') {
return Oas3Tools.sanitize(names.preferred, Oas3Tools.CaseStyle.PascalCase) // CASE: preferred name already known
} else if (typeof names.fromRef === 'string') {
return Oas3Tools.sanitize(names.fromRef, Oas3Tools.CaseStyle.PascalCase) // CASE: name from reference
} else if (typeof names.fromSchema === 'string') {
return Oas3Tools.sanitize(names.fromSchema, Oas3Tools.CaseStyle.PascalCase) // CASE: name from schema (i.e., "title" property in schema)
} else if (typeof names.fromPath === 'string') {
return Oas3Tools.sanitize(names.fromPath, Oas3Tools.CaseStyle.PascalCase) // CASE: name from path
} else {
return 'PlaceholderName' // CASE: placeholder name
}
}
/**
* Determines name to use for schema from previously determined schemaNames and