This repository was archived by the owner on Sep 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathSerializer.js
More file actions
1552 lines (1353 loc) · 46.6 KB
/
Serializer.js
File metadata and controls
1552 lines (1353 loc) · 46.6 KB
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
/**
* A Swagger v2 serializer.
* This implementation has the following limitations:
* - it will not create a global security field (securityDefinitions will be included though).
* - it will not use the externalDocs, as this is field is still not supported
* - the auths field in a Request **MUST** only be composed of References
* - null Auth not supported at the moment
*
* NOTE: we allow use of undefined in this file as it works nicely with JSON.stringify, which drops
* keys with a value of undefined.
* ```
* const swagger = { info, security }
* ```
* is easier to read than
* ```
* const swagger = { info }
* if (security) {
* swagger.security = security
* }
* ```
*
* NOTE: we make the assumption that keys of a container are equal to the uuids of the objects it
* holds.
*
* NOTE: we assume that keys of a response map are status codes
* NOTE: we assume that keys of a methods map are method names.
*/
/* eslint-disable no-undefined */
import { List, Set } from 'immutable'
import yaml from 'js-yaml'
import Constraint from '../../../models/Constraint'
import Reference from '../../../models/Reference'
import Auth from '../../../models/Auth'
import Parameter from '../../../models/Parameter'
import URL from '../../../models/URL'
import { currify, entries, convertEntryListInMap, flatten } from '../../../utils/fp-utils'
const __meta__ = {
format: 'swagger',
version: 'v2.0'
}
const methods = {}
// TODO move this to a better place
methods.getKeysFromRecord = (keyMap, record) => {
return entries(keyMap)
.map(({ key, value }) => ({ key, value: record.get(value) }))
.filter(({ value }) => typeof value !== 'undefined' && value !== null)
.reduce(convertEntryListInMap, {})
}
export class SwaggerSerializer {
static __meta__ = __meta__
static serialize(api) {
return methods.serialize(api)
}
static validate(content) {
return methods.validate(content)
}
}
/**
* converts a string written in JSON or YAML format into an object
* @param {string} str: the string to parse
* @returns {Object?} the converted object, or null if str was not a JSON or YAML string
*/
methods.parseJSONorYAML = (str) => {
let parsed
try {
parsed = JSON.parse(str)
}
catch (jsonParseError) {
try {
parsed = yaml.safeLoad(str)
}
catch (yamlParseError) {
return null
}
}
return parsed
}
/**
* looks (simplistically) at a Swagger file and gives it a quality score between 0 and 1.
* @param {SwaggerObject} swagger: the swagger file to analyze (here deconstructed)
* @returns {number} the quality of the swagger file wrt. to the version 2 format
*
* TODO: add reasons for low scores. Maybe use the format:
* {
* format: 'swagger',
* version: 'v2.0',
* score: [0-1],
* warnings: Array<string>
* }
*/
methods.getQualityScore = ({
swagger,
info,
paths,
host,
schemes,
securityDefinitions,
definitions,
parameters
}) => {
let score = 0
if (swagger !== '2.0' || !info || !paths) {
return score
}
const pathKeys = Object.keys(paths)
score = 1 - 1 / (pathKeys.length + 1)
score += host ? 0.1 : -0.1
score += schemes ? 0.1 : -0.1
score += securityDefinitions ? 0.1 : 0
score += definitions ? 0.1 : 0
score += parameters ? 0.1 : 0
score = Math.min(Math.max(score, 0), 1)
return score
}
/**
* returns a quality score for a content string wrt. to the swagger v2 format.
* @param {String} content: the content of the file to analyze
* @returns {number} the quality of the content
*/
methods.validate = (content) => {
const parsed = methods.parseJSONorYAML(content)
if (!parsed) {
return 0
}
return methods.getQualityScore(parsed)
}
/**
* creates a swagger format object
* @returns {string} the expected format object
*/
methods.getSwaggerFormatObject = () => {
return '2.0'
}
/**
* creates a default info object
* @returns {
* {
* title: string,
* version: string§
* }
* } the default info object
*/
methods.getDefaultInfoObject = () => {
return {
title: 'Unknown API',
version: 'v0.0.0'
}
}
/**
* creates a valid default contact object.
* @returns {SwaggerContactObject} the default valid contact object
*/
methods.getDefaultContactObject = () => {
return {}
}
/**
* extracts the swagger Contact object from an Info Record.
* @param {Info} $info: the info record to get the contact from.
* @returns {SwaggerContactObject} the corresponding contact object
*/
methods.getContactObject = ($info) => {
const $contact = $info.get('contact')
if (!$contact) {
return methods.getDefaultContactObject()
}
const keyMap = {
name: 'name',
url: 'url',
email: 'email'
}
return methods.getKeysFromRecord(keyMap, $contact)
}
/**
* creates a valid default license object.
* @returns {SwaggerLicenseObject} the default valid license object
*/
methods.getDefaultLicenseObject = () => {
return {
name: 'informal'
}
}
/**
* extracts the swagger License object from an Info Record.
* @param {Info} $info: the info record to get the license from.
* @returns {SwaggerLicenseObject} the corresponding license object
*/
methods.getLicenseObject = ($info) => {
const $license = $info.get('license')
if (!$license || !$license.get('name')) {
return methods.getDefaultLicenseObject()
}
const keyMap = {
name: 'name',
url: 'url'
}
return methods.getKeysFromRecord(keyMap, $license)
}
/**
* extracts the swagger Info object from an api.
* @param {Api} $api: the api to get the info from.
* @returns {SwaggerInfoObject} the corresponding info object
*/
methods.getInfoObject = ($api) => {
const $info = $api.get('info')
if (!$info) {
return methods.getDefaultInfoObject()
}
const keyMap = {
title: 'title',
description: 'description',
termsOfService: 'tos',
version: 'version'
}
const info = methods.getKeysFromRecord(keyMap, $info)
if ($info.get('contact')) {
info.contact = methods.getContactObject($info)
}
if ($info.get('license')) {
info.license = methods.getLicenseObject($info)
}
if (!info.title) {
info.title = 'Unknown API'
}
if (!info.version) {
info.version = 'v0.0.0'
}
return info
}
/**
* tests whether a Record is a Reference or not
* @param {Record} record: the record to test
* @returns {boolean} true if it is a Reference, false otherwise
*/
methods.isReference = (record) => record instanceof Reference
/**
* extracts endpoint references from a resource
* @param {Resource} resource: the resource from which to get the shared endpoints.
* @returns {OrderedMap<string, Reference>} the references to shared enpoints from this resource
*/
methods.getEnpointsSharedByResource = (resource) => {
return resource.get('endpoints').filter(methods.isReference)
}
/**
* extracts the Uuid of a reference
* @param {Reference} reference: the reference to find the uuid of
* @returns {string} the uuid of the reference
*/
methods.getUuidOfReference = (reference) => reference.get('uuid')
/**
* searches for the most used common endpoint.
* @param {Api} api: the api to fnid the most common endpoint of.
* @returns {URL} the most common endpoint, if there is one.
*/
methods.getMostCommonEndpoint = (api) => {
const resources = api.get('resources')
const bestEntry = resources
.valueSeq()
.map(methods.getEnpointsSharedByResource)
.flatten(true)
.map(methods.getUuidOfReference)
.countBy(v => v)
.reduce((best, value, key) => best.value > value ? best : { key, value }, {})
const sharedEndpoint = api.getIn([ 'store', 'endpoint', bestEntry.key ])
if (sharedEndpoint) {
return sharedEndpoint
}
const sharedVariable = api.getIn([ 'store', 'variable', bestEntry.key ])
if (!sharedVariable) {
return null
}
const firstValueInVariable = sharedVariable.get('values').valueSeq().get(0)
if (!firstValueInVariable) {
return null
}
return new URL({ url: firstValueInVariable })
}
/**
* removes `:` from the protocol if it ends with it.
* @param {string} protocol: the protocol to strip.
* @return {string} the normalized protocol
*/
methods.removeDotsFromProtocol = (protocol) => {
if (protocol[protocol.length - 1] === ':') {
return protocol.slice(0, protocol.length - 1)
}
return protocol
}
/**
* gets the schemes of an enpoint.
* @param {URL} endpoint: the endpoint to get the schemes of.
* @returns {Array<string>} the corresponding schemes
*/
methods.getSchemesFromEndpoint = (endpoint) => {
return endpoint.get('protocol')
.map(methods.removeDotsFromProtocol)
.toJS()
}
/**
* returns the host and pathname of an endpoint.
* @param {URL} endpoint: the endpoint to get the host and pathname from.
* @return {
* {
* host: string?,
* basePath: string?
* }
* } the host and basePath associated with this endpoint
*
* TODO: the host and basePath string should not be templated. use generate instead of toURLObject
*/
methods.getHostAndBasePathFromEndpoint = (endpoint) => {
const delimiters = List([ '{', '}' ])
const urlObject = endpoint.toURLObject(delimiters)
return {
host: urlObject.host || undefined,
basePath: urlObject.pathname || undefined
}
}
/**
* extracts endpoint related fields out of an Api Record.
* @param {Api} api: the Api to get the protocol, host, and basePath from.
* @returns {
* {
* schemes: Array<string>?,
* host: string?,
* basePath: string?
* }
* } the global endpoint fields
*/
methods.getEndpointRelatedObjects = (api) => {
const endpoint = methods.getMostCommonEndpoint(api)
if (!endpoint) {
return {}
}
const schemes = methods.getSchemesFromEndpoint(endpoint)
const { host, basePath } = methods.getHostAndBasePathFromEndpoint(endpoint)
return { schemes, host, basePath }
}
/**
* extracts shared JSON Schemas from the store of an API and returns them as a Definitions Object.
* @param {Api} api: the api to get the JSON Schemas from
* @returns {SwaggerDefinitionsObject} the definitions of this Api.
*/
methods.getDefinitions = (api) => {
const constraints = api.getIn([ 'store', 'constraint' ])
.filter(constraint => constraint instanceof Constraint.JSONSchema)
.map((constraint, key) => {
return { key, value: constraint.toJSONSchema() }
})
.reduce(convertEntryListInMap, {})
if (Object.keys(constraints).length === 0) {
return undefined
}
return constraints
}
/**
* extracts the headers of a response, and converts them into HeaderObjects.
* @param {Store} store: the store to use to resolve references
* @param {Response} response: the response to get the headers of.
* @returns {SwaggerHeadersObject} the object holding all headers of the response
*
* TODO: take contexts into account.
* TODO: filter out content-type param
*/
methods.getHeadersFromResponse = (store, response) => {
const headers = response.getIn([ 'parameters', 'headers' ])
.map((param) => {
let resolved = param
if (param instanceof Reference) {
resolved = store.getIn([ 'parameter', param.get('uuid') ])
}
if (!resolved || resolved.get('key') === 'Content-Type') {
return null
}
return methods.convertParameterToHeaderObject(resolved)
})
.filter(v => !!v)
.reduce(convertEntryListInMap, {})
if (Object.keys(headers).length === 0) {
return undefined
}
return headers
}
/**
* extracts a Schema from a response.
* @param {Response} response: the response to get a schema from
* @returns {JSONSchema?} the corresponding json schema, if it exists.
*
* TODO: take contexts into account.
*/
methods.getSchemaFromResponse = (response) => {
const schema = response.getIn([ 'parameters', 'body' ])
.valueSeq()
.map(param => param.getJSONSchema(false))
.toJS()[0]
return schema
}
/**
* converts a response record into a response object.
* @param {Store} store: the store to use to resolve references
* @param {string} key: the key of the response record in its container (either a store, or a
* request)
* @param {Response} value: the response record to convert into a response object
* @returns {SwaggerResponseObject} the corresponding swagger response object.
*/
methods.convertResponseRecordToResponseObject = (store, { key, value }) => {
const response = {
description: value.get('description') || '',
headers: methods.getHeadersFromResponse(store, value),
schema: methods.getSchemaFromResponse(value)
}
return {
key,
value: response
}
}
/**
* extract shared responses from an api and stores them in a Response Definitions Object.
* @param {Api} api: the api to get the shared responses from.
* @returns {SwaggerResponseDefinitionsObject} the corresponding response definitions object.
*/
methods.getResponseDefinitions = (api) => {
const store = api.get('store')
const convertResponseRecordToResponseObject = currify(
methods.convertResponseRecordToResponseObject, store
)
const responses = store.get('response')
.map((value, key) => ({ key, value }))
.map(convertResponseRecordToResponseObject)
.reduce(convertEntryListInMap, {})
if (Object.keys(responses).length === 0) {
return undefined
}
return responses
}
/**
* converts a BasicAuth into a valid security definition.
* @param {BasicAuth} auth: the auth to converts
* @returns {SwaggerSecurityDefinitionObject} the corresponding security definition
*/
methods.convertBasicAuth = (auth) => {
const securityScheme = {
type: 'basic'
}
if (auth.get('description')) {
securityScheme.description = auth.get('description')
}
return {
key: auth.get('authName'),
value: securityScheme
}
}
/**
* converts an ApiKeyAuth into a valid security definition.
* @param {ApiKeyAuth} auth: the auth to converts
* @returns {SwaggerSecurityDefinitionObject} the corresponding security definition
*/
methods.convertApiKeyAuth = (auth) => {
const keyMap = {
description: 'description',
name: 'name',
in: 'in'
}
const securityScheme = methods.getKeysFromRecord(keyMap, auth)
securityScheme.type = 'apiKey'
return {
key: auth.get('authName'),
value: securityScheme
}
}
/**
* converts an OAuth2Auth into a valid security definition.
* @param {OAuth2Auth} auth: the auth to converts
* @returns {SwaggerSecurityDefinitionObject} the corresponding security definition
*/
methods.convertOAuth2Auth = (auth) => {
const keyMap = {
description: 'description',
flow: 'flow',
authorizationUrl: 'authorizationUrl',
tokenUrl: 'tokenUrl'
}
const securityScheme = methods.getKeysFromRecord(keyMap, auth)
securityScheme.type = 'oauth2'
securityScheme.scopes = auth.get('scopes').reduce(convertEntryListInMap, {})
return {
key: auth.get('authName'),
value: securityScheme
}
}
/**
* converts an Auth into a valid security definition.
* @param {Auth} auth: the auth to converts
* @returns {SwaggerSecurityDefinitionObject?} the corresponding security definition
*
* TODO deal with unknown auth methods
*/
methods.convertAuthToSecurityRequirementEntry = (auth) => {
if (auth instanceof Auth.Basic) {
return methods.convertBasicAuth(auth)
}
if (auth instanceof Auth.ApiKey) {
return methods.convertApiKeyAuth(auth)
}
if (auth instanceof Auth.OAuth2) {
return methods.convertOAuth2Auth(auth)
}
return null
}
/**
* gets shared auth methods from the api.
* @param {Api} api: the api to get the shared authentication methods from.
* @returns {SwaggerSecurityDefinitionsObject?} the corresponding security definitions object if it
* should exist.
*/
methods.getSecurityDefinitions = (api) => {
const securityDefinitions = api.getIn([ 'store', 'auth' ])
.map(methods.convertAuthToSecurityRequirementEntry)
.filter(value => !!value)
.reduce(convertEntryListInMap, {})
if (Object.keys(securityDefinitions).length === 0) {
return undefined
}
return securityDefinitions
}
/**
* converts a Parameter record into a Schema parameter (subset of the Parameter Object
* implementation in swagger that only has certain fields, that are wildly different from the
* more standard Parameter Object spec for query, path and header params)
*
* @param {Parameter} parameter: the parameter to convert into a schema parameter.
* @param {string} key: the key of the Parameter in its container.
* @returns {Entry<string, SwaggerSchemaParameterObject>} the corresponding parameter object.
*
* NOTE: This method has parameter as [value, key] instead of {key, value} because it is invoked
* on an Immutable structure.
*/
methods.convertParameterToSchemaParameter = (parameter, key) => {
const keyMap = {
description: 'description',
required: 'required'
}
const param = methods.getKeysFromRecord(keyMap, parameter)
param.schema = parameter.getJSONSchema(false)
param.in = 'body'
param.name = parameter.get('key') || parameter.get('name') || 'body'
return { key, value: param }
}
/**
* tests whether a Parameter is a body or a formData parameter, by checking if it is restrained to
* form-data or urlEncoded contexts.
* @param {Parameter} parameter: the parameter to test
* @return {boolean} true if it is a body param, false otherwise
*/
methods.isBodyParameter = (parameter) => {
if (parameter.get('in') !== 'body') {
return false
}
if (parameter.get('applicableContexts').size === 0) {
return true
}
const isFormData = parameter.isValid(
new Parameter({
key: 'Content-Type',
default: 'multipart/form-data'
})
)
const isUrlEncoded = parameter.isValid(
new Parameter({
key: 'Content-Type',
default: 'multipart/form-data'
})
)
return !isFormData && !isUrlEncoded
}
/**
* maps a ParameterContainer location to a swagger location (for the parameter.in field)
* @param {Parameter} parameter: the parameter to get the correct location for
* @returns {'query'|'header'|'path'|'formData'?} the corresponding location
*
* NOTE: this method assumes that body parameters have been filtered to weed out Schema Parameters.
*/
methods.getParamLocation = (parameter) => {
const locationMap = {
queries: 'query',
headers: 'header',
path: 'path',
body: 'formData'
}
return locationMap[parameter.get('in')]
}
/**
* returns common parameter fields that are used by parameters, items object, and headers object
* @param {Parameter} parameter: the parameter to get the fields from
* @returns {CommonParameterObject} the fields that are shared by all types of "parameter" objects.
*
* NOTE: the following fields are not included:
* - name
* - in
* - description
* - required
*/
methods.getCommonFieldsFromParameter = (parameter) => {
if (!parameter) {
return {}
}
const schema = parameter.getJSONSchema(false)
const {
type,
maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf,
maxLength, minLength, pattern,
maxItems, minItems, uniqueItems
} = schema
const commonFields = {
type: type !== 'object' ? type : 'string',
'x-real-type': type === 'object' ? type : undefined,
maximum, minimum, exclusiveMinimum, exclusiveMaximum, multipleOf,
maxLength, minLength, pattern,
maxItems, minItems, uniqueItems,
default: schema.default, enum: schema.enum
}
return commonFields
}
/**
* converts a Parameter Object to a Swagger Items Object.
* @param {Parameter} parameter: the parameter to convert
* @returns {Entry<null, SwaggerItemsObject>} the corresponding items object.
*
* NOTE: this methods adds no fields to the common fields generated from the parameter.
*/
methods.convertParameterToItemsObject = (parameter) => {
if (parameter instanceof Reference) {
return { value: '#/parameters/' + parameter.get('uuid') }
}
const value = methods.getCommonFieldsFromParameter(parameter)
return { value }
}
/**
* converts a Parameter Object to a Swagger Header Object.
* @param {Parameter} parameter: the parameter to convert
* @param {string} key: the key of the parameter in its container
* @returns {Entry<string, SwaggerHeaderObject>} the corresponding header object.
*
* NOTE: this methods adds the following fields to the common fields from a parameter.
* - description
*
* NOTE: This method has parameter as [value, key] instead of {key, value} because it is invoked
* on an Immutable structure.
*/
methods.convertParameterToHeaderObject = (parameter) => {
const key = parameter.get('key')
const value = methods.getCommonFieldsFromParameter(parameter)
value.description = parameter.get('description') || undefined
return { key, value }
}
/**
* converts a Parameter Object to a standard Swagger Parameter Object.
* @param {Parameter} parameter: the parameter to convert
* @param {string} key: the key of the parameter in its container
* @returns {Entry<string, SwaggerParameterObject>} the corresponding parameter object.
*
* NOTE: this methods adds the following fields to the common fields from a parameter.
* - name
* - description
* - required
* - in
* - items (if type is array)
*
* NOTE: This method has parameter as [value, key] instead of {key, value} because it is invoked
* on an Immutable structure.
*/
methods.convertParameterToStandardParameterObject = (parameter, key) => {
const value = methods.getCommonFieldsFromParameter(parameter)
value.name = parameter.get('key') || undefined
value.description = parameter.get('description') || undefined
value.required = parameter.get('required') !== 'null' ? parameter.get('required') : undefined
value.in = methods.getParamLocation(parameter)
if (value.type === 'array') {
const itemsEntry = methods.convertParameterToItemsObject(parameter.get('value'))
value.items = itemsEntry.value
}
return { key, value }
}
/**
* converts a Parameter Object to a Swagger Parameter Object.
* @param {Parameter} parameter: the parameter to convert
* @param {string} key: the key of the parameter in its container
* @returns {Entry<string, SwaggerParameterObject>} the corresponding parameter object.
*
* NOTE: This method has parameter as [value, key] instead of {key, value} because it is invoked
* on an Immutable structure.
*/
methods.convertParameterToParameterObject = (parameter, key) => {
if (methods.isBodyParameter(parameter)) {
return methods.convertParameterToSchemaParameter(parameter, key)
}
return methods.convertParameterToStandardParameterObject(parameter, key)
}
/**
* gets the shared parameter defintions from an Api and stores them in a ParameterDefinitions Object
* @param {Api} api: the api to get the shared parameters from
* @returns {SwaggerParameterDefinitionsObject?} the corresponding parameter definition object, if
* it should exist
*/
methods.getParameterDefinitions = (api) => {
const parameterDefinitions = api.getIn([ 'store', 'parameter' ])
.filter(param => !methods.isConsumesHeader(param) && !methods.isProducesHeader(param))
.map(methods.convertParameterToParameterObject)
.filter(value => !!value)
.reduce(convertEntryListInMap, {})
if (Object.keys(parameterDefinitions).length === 0) {
return undefined
}
return parameterDefinitions
}
/**
* tests whether an interface can be used for tags or not. (the interface has to be at the request
* or resource level to be applicable)
* @param {Interface} itf: the interface to test
* @returns {boolean} true if the itf can be converted in a tag.
*/
methods.isUseableAsTag = (itf) => {
return !!itf && (itf.get('level') === 'request' || itf.get('level') === 'resource')
}
/**
* converts an Interface into a tag.
* @param {Interface} itf: the interface to convert.
* @returns {SwaggerTagObject} the corresponding tag
*/
methods.convertInterfaceToTagObject = (itf) => {
const keyMap = {
name: 'uuid',
description: 'description'
}
const tag = methods.getKeysFromRecord(keyMap, itf)
if (!tag.name) {
tag.name = 'unnamedTag'
}
return tag
}
/**
* gets tag definitions from an api
* @param {Api} api: the api to get the tags from
* @returns {SwaggerTagDefinitionsObject} the corresponding tags
*
* NOTE: this only defines shared interfaces that are at the Resource or Request level.
* This does not create a tag definition for non shared interfaces (which should be very rare)
* This is however not an issue, since having a tag definition is not a requirement for tags defined
* in an operation object
*/
methods.getTagDefinitions = (api) => {
const tagDefinitions = api.getIn([ 'store', 'interface' ])
.filter(methods.isUseableAsTag)
.map(methods.convertInterfaceToTagObject)
.valueSeq()
.toJS()
return tagDefinitions
}
/**
* extracts the path from a Resource.
* @param {Resource} resource: the resource to get the path from.
* @returns {string?} the corresponding path
*/
methods.getPathFromResource = (resource) => {
const path = resource.get('path').toURLObject(List([ '{', '}' ])).pathname
return path
}
/**
* converts an interface or reference into a tag string
* @param {Interface|Reference} interfaceOrReference: the interface or reference to convert
* @return {string} the corresponding tag string
*
* NOTE: a Tag string is different from a Tag Definition
*/
methods.convertInterfaceToTagString = (interfaceOrReference) => interfaceOrReference.get('uuid')
/**
* extracts all tags from a resource or request object
* @param {Resource|Request} resourceOrRequest: the Resource or Request to get the tags from.
* @returns {Array<string>} the corresponding tag strings.
*/
methods.getTagStrings = (resourceOrRequest) => {
return resourceOrRequest.get('interfaces')
.valueSeq()
.map(methods.convertInterfaceToTagString)
.filter(tag => !!tag)
.toJS()
}
/**
* adds tags from a resource or a request to an operation
* @param {Resource|Request} resourceOrRequest: the Resource or Request to get the tags from.
* @param {SwaggerOperationObject} operation: the operation object to update
* @returns {SwaggerOperationObject} the update operation object
*/
methods.addTagsToOperation = (resourceOrRequest, operation) => {
const tags = methods.getTagStrings(resourceOrRequest)
if (tags.length === 0) {
return operation
}
operation.tags = [].concat(operation.tags || [], tags)
return operation
}
/**
* tests whether two array have the same objects, regardless of order or repetition.
* @param {Array<*>} first: the first array to compare
* @param {Array<*>} second: the second array to compare
* @returns {boolean} returns true if both arrays have the same set of objects, returns false
* otherwise
*/
methods.equalSet = (first, second) => {
return Set(first).equals(Set(second))
}
/**
* extracts the consumes entry of an operation. Returns nothing if the consumes field is not defined
* or if it is identical to the globally defined consumes field
* @param {Array<string>} globalConsumes: the globally defined consumes field.
* @param {ParameterContainer} container: the parameter container that holds the headers of this
* request, which potentially include a Content-Type header.
* @returns {Array<string>?} the corresponding consumes field
*/
methods.getConsumesEntry = (globalConsumes, container) => {
const headers = container.get('headers')
const consumes = methods.getContentTypeFromFilteredParams(headers, methods.isConsumesHeader)
if (consumes.length && !methods.equalSet(consumes, globalConsumes)) {
return Array.from(new Set(consumes))
}
return undefined
}
/**
* extracts the produces entry of an operation. Returns nothing if the produces field is not defined
* or if it is identical to the globally defined produces field
* @param {Store} store: the store to use to resolve references
* @param {Request} request: the request from which to get the responses and their respective
* headers, which potentially include Content-Type headers.
* @param {Array<string>} globalProduces: the globally defined produces field.
* @returns {Array<string>?} the corresponding produces field
*/
methods.getProducesEntry = (store, request, globalProduces) => {
const produces = request.get('responses')
.map(response => response.get('parameters').resolve(store).get('headers'))
.map(headers => methods.getContentTypeFromFilteredParams(headers, methods.isProducesHeader))
.reduce(flatten, [])
if (produces.length && !methods.equalSet(produces, globalProduces)) {
return Array.from(new Set(produces))
}
return undefined
}
/**
* converts a reference into a Parameter Reference Object, which in this case is just a $ref field
* @param {Reference} reference: the reference to convert into a parameter reference object.
* @returns {Entry<null, SwaggerReferenceObject>} the corresponding reference object.
*/
methods.convertReferenceToParameterObject = (reference) => {
return {
value: {
$ref: '#/parameters/' + reference.get('uuid')
}
}
}
/**
* converts a Reference or a Parameter into a swagger parameter (reference) object.
* @param {Parameter|Reference} parameterOrReference: the parameter or reference to convert,
* @param {string} key: the key of the parameter in the container that holds it.
* @returns {SwaggerReferenceObject|SwaggerParameterObject} the corresponding parameter object
*
* NOTE: This method has parameter as [value, key] instead of {key, value} because it is invoked
* on an Immutable structure.
*/