-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
generate.ts
1025 lines (919 loc) · 29.5 KB
/
generate.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
import _ from "lodash";
import ts, { factory } from "typescript";
import path from "path";
import { OpenAPIV3 } from "openapi-types";
import * as cg from "./tscodegen";
import generateServers, { defaultBaseUrl } from "./generateServers";
import { Opts } from ".";
import { threadId } from "worker_threads";
export const verbs = [
"GET",
"PUT",
"POST",
"DELETE",
"OPTIONS",
"HEAD",
"PATCH",
"TRACE",
];
type ContentType = "json" | "form" | "multipart";
export const contentTypes: Record<string, ContentType> = {
"*/*": "json",
"application/json": "json",
"application/hal+json": "json",
"application/problem+json": "json",
"application/geo+json": "json",
"application/x-www-form-urlencoded": "form",
"multipart/form-data": "multipart",
};
// augment SchemaObject type to allow slowly adopting new OAS3.1+ features
type SchemaObject = OpenAPIV3.SchemaObject & {
const?: unknown;
};
/**
* Get the name of a formatter function for a given parameter.
*/
export function getFormatter({
style = "form",
explode = true,
}: OpenAPIV3.ParameterObject) {
if (explode && style === "deepObject") return "deep";
if (explode) return "explode";
if (style === "simple") return "simple";
if (style === "spaceDelimited") return "space";
if (style === "pipeDelimited") return "pipe";
return "form";
}
export function getOperationIdentifier(id?: string) {
if (!id) return;
if (id.match(/[^\w\s]/)) return;
id = _.camelCase(id);
if (cg.isValidIdentifier(id)) return id;
}
/**
* Create a method name for a given operation, either from its operationId or
* the HTTP verb and path.
*/
export function getOperationName(
verb: string,
path: string,
operationId?: string
) {
const id = getOperationIdentifier(operationId);
if (id) return id;
path = path.replace(/\{(.+?)\}/, "by $1").replace(/\{(.+?)\}/, "and $1");
return _.camelCase(`${verb} ${path}`);
}
export function isNullable(schema: any) {
return !!(schema && schema.nullable);
}
export function isReference(obj: any): obj is OpenAPIV3.ReferenceObject {
return obj && "$ref" in obj;
}
//See https://swagger.io/docs/specification/using-ref/
export function getReference(spec: any, ref: string) {
const path = ref
.slice(2)
.split("/")
.map((s) => unescape(s.replace(/~1/g, "/").replace(/~0/g, "~")));
const ret = _.get(spec, path);
if (typeof ret === "undefined") {
throw new Error(`Can't find ${path}`);
}
return ret;
}
/**
* If the given object is a ReferenceObject, return the last part of its path.
*/
export function getReferenceName(obj: any) {
if (isReference(obj)) {
return _.camelCase(obj.$ref.split("/").slice(-1)[0]);
}
}
const formatPrimitivePathParameter = (name: string) => {
const expression = _.camelCase(name);
return cg.createCall(factory.createIdentifier("encodeURIComponent"), {
args: [factory.createIdentifier(expression)],
});
};
/**
* Create a template string literal from the given OpenAPI urlTemplate.
* Curly braces in the path are turned into identifier expressions,
* which are read from the local scope during runtime.
*/
export function createUrlExpression(
path: string,
qs?: ts.Expression,
formatPathParameter: (
name: string
) => ts.Expression = formatPrimitivePathParameter
) {
const spans: Array<{ expression: ts.Expression; literal: string }> = [];
// Use a replacer function to collect spans as a side effect:
const head = path.replace(
/(.*?)\{(.+?)\}(.*?)(?=\{|$)/g,
(_substr, head, name, literal) => {
spans.push({
expression: formatPathParameter(name),
literal,
});
return head;
}
);
if (qs) {
// add the query string as last span
spans.push({ expression: qs, literal: "" });
}
return cg.createTemplateString(head, spans);
}
/**
* Create a call expression for one of the QS runtime functions.
*/
export function callQsFunction(name: string, args: ts.Expression[]) {
return cg.createCall(
factory.createPropertyAccessExpression(
factory.createIdentifier("QS"),
name
),
{ args }
);
}
/**
* Create a call expression for one of the oazapfts runtime functions.
*/
export function callOazapftsFunction(
name: string,
args: ts.Expression[],
typeArgs?: ts.TypeNode[]
) {
return cg.createCall(
factory.createPropertyAccessExpression(
factory.createIdentifier("oazapfts"),
name
),
{ args, typeArgs }
);
}
/**
* Despite its name, OpenApi's `deepObject` serialization does not support
* deeply nested objects. As a workaround we detect parameters that contain
* square brackets and merge them into a single object.
*/
export function supportDeepObjects(params: OpenAPIV3.ParameterObject[]) {
const res: OpenAPIV3.ParameterObject[] = [];
const merged: any = {};
params.forEach((p) => {
const m = /^(.+?)\[(.*?)\]/.exec(p.name);
if (!m) {
res.push(p);
return;
}
const [, name, prop] = m;
let obj = merged[name];
if (!obj) {
obj = merged[name] = {
name,
in: p.in,
style: "deepObject",
schema: {
type: "object",
properties: {},
},
};
res.push(obj);
}
obj.schema.properties[prop] = p.schema;
});
return res;
}
/**
* Main entry point that generates TypeScript code from a given API spec.
*/
export default class ApiGenerator {
constructor(
public readonly spec: OpenAPIV3.Document,
public readonly opts: Opts = {},
/** Indicates if the document was converted from an older version of the OpenAPI specification. */
public readonly isConverted = false
) {}
aliases: ts.TypeAliasDeclaration[] = [];
enumAliases: ts.Statement[] = [];
typeEnumAliases: Record<string, number> = {};
enumRefs: Record<string, { values: string; type: ts.TypeReferenceNode }> = {};
// Collect the types of all referenced schemas so we can export them later
refs: Record<string, ts.TypeReferenceNode> = {};
// Keep track of already used type aliases
typeAliases: Record<string, number> = {};
reset() {
this.aliases = [];
this.enumAliases = [];
this.refs = {};
this.typeAliases = {};
}
resolve<T>(obj: T | OpenAPIV3.ReferenceObject) {
if (!isReference(obj)) return obj;
const ref = obj.$ref;
if (!ref.startsWith("#/")) {
throw new Error(
`External refs are not supported (${ref}). Make sure to call SwaggerParser.bundle() first.`
);
}
return getReference(this.spec, ref) as T;
}
resolveArray<T>(array?: Array<T | OpenAPIV3.ReferenceObject>) {
return array ? array.map((el) => this.resolve(el)) : [];
}
skip(tags?: string[]) {
const excluded = tags && tags.some((t) => this.opts?.exclude?.includes(t));
if (excluded) {
return true;
}
if (this.opts?.include) {
const included = tags && tags.some((t) => this.opts.include?.includes(t));
return !included;
}
return false;
}
getUniqueAlias(name: string) {
let used = this.typeAliases[name] || 0;
if (used) {
this.typeAliases[name] = ++used;
name += used;
}
this.typeAliases[name] = 1;
return name;
}
getEnumUniqueAlias(name: string, values: string) {
// If the enum does not exist
if (!this.enumRefs[name]) {
this.typeEnumAliases[name] = 1;
return name;
// If enum name already exists and have the same values
} else if (this.enumRefs[name] && this.enumRefs[name].values == values) {
return name;
// If the already exists but has a different value: eg Status2
} else {
this.typeEnumAliases[name] += 1;
name += this.typeEnumAliases[name];
return name;
}
}
getRefBasename(ref: string): string {
return ref.replace(/.+\//, "");
}
/**
* Create a type alias for the schema referenced by the given ReferenceObject
*/
getRefAlias(obj: OpenAPIV3.ReferenceObject) {
const { $ref } = obj;
let ref = this.refs[$ref];
if (!ref) {
const schema = this.resolve<SchemaObject>(obj);
const name = this.getUniqueAlias(
_.upperFirst(_.camelCase(schema.title || this.getRefBasename($ref)))
);
ref = this.refs[$ref] = factory.createTypeReferenceNode(name, undefined);
const type = this.getTypeFromSchema(schema);
this.aliases.push(
cg.createTypeAliasDeclaration({
modifiers: [cg.modifier.export],
name,
type,
})
);
}
return ref;
}
getUnionType(
variants: (OpenAPIV3.ReferenceObject | SchemaObject)[],
discriminator?: OpenAPIV3.DiscriminatorObject
): ts.TypeNode {
if (discriminator) {
// oneOf + discriminator -> tagged union (polymorphism)
if (discriminator.propertyName === undefined) {
throw new Error("Discriminators require a propertyName");
}
// By default, the last component of the ref name (i.e., after the last trailing slash) is
// used as the discriminator value for each variant. This can be overridden using the
// discriminator.mapping property.
const mappedValues = new Set(
Object.values(discriminator.mapping || {}).map((ref) =>
this.getRefBasename(ref)
)
);
return factory.createUnionTypeNode(
(
[
...Object.entries(discriminator.mapping || {}).map(
([discriminatorValue, variantRef]) => [
discriminatorValue,
{ $ref: variantRef },
]
),
...variants
.filter((variant) => {
if (!isReference(variant)) {
// From the Swagger spec: "When using the discriminator, inline schemas will not be
// considered."
throw new Error(
"Discriminators require references, not inline schemas"
);
}
return !mappedValues.has(this.getRefBasename(variant.$ref));
})
.map((schema) => [
this.getRefBasename((schema as OpenAPIV3.ReferenceObject).$ref),
schema,
]),
] as [string, OpenAPIV3.ReferenceObject][]
).map(([discriminatorValue, variant]) =>
// Yields: { [discriminator.propertyName]: discriminatorValue } & variant
factory.createIntersectionTypeNode([
factory.createTypeLiteralNode([
cg.createPropertySignature({
name: discriminator.propertyName,
type: factory.createLiteralTypeNode(
factory.createStringLiteral(discriminatorValue)
),
}),
]),
this.getTypeFromSchema(variant),
])
)
);
} else {
// oneOf -> untagged union
return factory.createUnionTypeNode(
variants.map((schema) => this.getTypeFromSchema(schema))
);
}
}
/**
* Creates a type node from a given schema.
* Delegates to getBaseTypeFromSchema internally and
* optionally adds a union with null.
*/
getTypeFromSchema(
schema?: SchemaObject | OpenAPIV3.ReferenceObject,
name?: string
): ts.TypeNode {
const type = this.getBaseTypeFromSchema(schema, name);
return isNullable(schema)
? factory.createUnionTypeNode([type, cg.keywordType.null])
: type;
}
/**
* This is the very core of the OpenAPI to TS conversion - it takes a
* schema and returns the appropriate type.
*/
getBaseTypeFromSchema(
schema?: SchemaObject | OpenAPIV3.ReferenceObject,
name?: string
): ts.TypeNode {
if (!schema) return cg.keywordType.any;
if (isReference(schema)) {
return this.getRefAlias(schema);
}
if (schema.oneOf) {
// oneOf -> union
return this.getUnionType(schema.oneOf, schema.discriminator);
}
if (schema.anyOf) {
// anyOf -> union
return factory.createUnionTypeNode(
schema.anyOf.map((schema) => this.getTypeFromSchema(schema))
);
}
if (schema.allOf) {
// allOf -> intersection
const types = schema.allOf.map((schema) =>
this.getTypeFromSchema(schema)
);
if (schema.properties || schema.additionalProperties) {
// properties -> literal type
types.push(
this.getTypeFromProperties(
schema.properties || {},
schema.required,
schema.additionalProperties
)
);
}
return factory.createIntersectionTypeNode(types);
}
if ("items" in schema) {
// items -> array
return factory.createArrayTypeNode(this.getTypeFromSchema(schema.items));
}
if (schema.properties || schema.additionalProperties) {
// properties -> literal type
return this.getTypeFromProperties(
schema.properties || {},
schema.required,
schema.additionalProperties
);
}
if (schema.enum) {
return this.opts.useEnumType && name && schema.type != "boolean"
? this.getTrueEnum(schema, name)
: this.getTypeFromEnum(schema.enum);
}
if (schema.format == "binary") {
return factory.createTypeReferenceNode("Blob", []);
}
if (schema.const) {
return this.getTypeFromEnum([schema.const]);
}
if (schema.type) {
// string, boolean, null, number
if (schema.type in cg.keywordType) return cg.keywordType[schema.type];
if (schema.type === "integer") return cg.keywordType.number;
}
return cg.keywordType.any;
}
/**
* Creates literal type (or union) from an array of values
*/
getTypeFromEnum(values: unknown[]) {
const types = values.map((s) => {
if (s === null) return cg.keywordType.null;
if (typeof s === "boolean")
return s
? factory.createLiteralTypeNode(
ts.factory.createToken(ts.SyntaxKind.TrueKeyword)
)
: factory.createLiteralTypeNode(
ts.factory.createToken(ts.SyntaxKind.FalseKeyword)
);
if (typeof s === "number")
return factory.createLiteralTypeNode(factory.createNumericLiteral(s));
if (typeof s === "string")
return factory.createLiteralTypeNode(factory.createStringLiteral(s));
throw new Error(`Unexpected ${String(s)} of type ${typeof s} in enum`);
});
return types.length > 1 ? factory.createUnionTypeNode(types) : types[0];
}
getEnumValuesString(values: string[]): string {
return values.join("_");
}
/*
Creates a enum "ref" if not used, reuse existing if values and name matches or creates a new one
with a new name adding a number
*/
getTrueEnum(schema: OpenAPIV3.NonArraySchemaObject, propName: string) {
const proposedName = schema.title || _.upperFirst(propName);
const stringEnumValue = this.getEnumValuesString(
schema.enum ? schema.enum : []
);
const name = this.getEnumUniqueAlias(proposedName, stringEnumValue);
if (this.enumRefs[proposedName] && proposedName === name) {
return this.enumRefs[proposedName].type;
}
const values = schema.enum ? schema.enum : [];
const members = values.map((s, index) => {
if (schema.type === "boolean") {
s = Boolean(s) ? "true" : "false";
} else if (schema.type === "string") {
s = _.upperFirst(s);
}
return factory.createEnumMember(
factory.createIdentifier(s),
schema.type === "number"
? factory.createNumericLiteral(index)
: factory.createStringLiteral(s)
);
});
this.enumAliases.push(
factory.createEnumDeclaration(
undefined,
[cg.modifier.export],
name,
members
)
);
const type = factory.createTypeReferenceNode(name, undefined);
this.enumRefs[proposedName] = {
values: stringEnumValue,
type: factory.createTypeReferenceNode(name, undefined),
};
return type;
}
/**
* Recursively creates a type literal with the given props.
*/
getTypeFromProperties(
props: {
[prop: string]: SchemaObject | OpenAPIV3.ReferenceObject;
},
required?: string[],
additionalProperties?: boolean | SchemaObject | OpenAPIV3.ReferenceObject
) {
const members: ts.TypeElement[] = Object.keys(props).map((name) => {
const schema = props[name];
const isRequired = required && required.includes(name);
let type = this.getTypeFromSchema(schema, name);
if (!isRequired && this.opts.unionUndefined) {
type = factory.createUnionTypeNode([type, cg.keywordType.undefined]);
}
return cg.createPropertySignature({
questionToken: !isRequired,
name,
type,
});
});
if (additionalProperties) {
const type =
additionalProperties === true
? cg.keywordType.any
: this.getTypeFromSchema(additionalProperties);
members.push(cg.createIndexSignature(type));
}
return factory.createTypeLiteralNode(members);
}
getTypeFromResponses(responses: OpenAPIV3.ResponsesObject) {
return factory.createUnionTypeNode(
Object.entries(responses).map(([code, res]) => {
const statusType =
code === "default"
? cg.keywordType.number
: factory.createLiteralTypeNode(factory.createNumericLiteral(code));
const props = [
cg.createPropertySignature({
name: "status",
type: statusType,
}),
];
const dataType = this.getTypeFromResponse(res);
if (dataType !== cg.keywordType.void) {
props.push(
cg.createPropertySignature({
name: "data",
type: dataType,
})
);
}
return factory.createTypeLiteralNode(props);
})
);
}
getTypeFromResponse(
resOrRef: OpenAPIV3.ResponseObject | OpenAPIV3.ReferenceObject
) {
const res = this.resolve(resOrRef);
if (!res || !res.content) return cg.keywordType.void;
return this.getTypeFromSchema(this.getSchemaFromContent(res.content));
}
getResponseType(
responses?: OpenAPIV3.ResponsesObject
): "json" | "text" | "blob" {
// backwards-compatibility
if (!responses) return "text";
const resolvedResponses = Object.values(responses).map((response) =>
this.resolve(response)
);
// if no content is specified, assume `text` (backwards-compatibility)
if (
!resolvedResponses.some(
(res) => Object.keys(res.content ?? []).length > 0
)
) {
return "text";
}
const isJson = resolvedResponses.some((response) => {
const responseMimeTypes = Object.keys(response.content ?? {});
return responseMimeTypes.some(
(mimeType) => contentTypes[mimeType] === "json"
);
});
// if there’s `application/json` or `*/*`, assume `json`
if (isJson) {
return "json";
}
// if there’s `text/*`, assume `text`
if (
resolvedResponses.some((res) =>
Object.keys(res.content ?? []).some((type) => type.startsWith("text/"))
)
) {
return "text";
}
// for the rest, assume `blob`
return "blob";
}
getSchemaFromContent(content: any) {
const contentType = Object.keys(contentTypes).find((t) => t in content);
let schema;
if (contentType) {
schema = _.get(content, [contentType, "schema"]);
}
if (schema) {
return schema;
}
// if no content is specified -> string
// `text/*` -> string
if (
Object.keys(content).length === 0 ||
Object.keys(content).some((type) => type.startsWith("text/"))
) {
return { type: "string" };
}
// rest (e.g. `application/octet-stream`, `application/gzip`, …) -> binary
return { type: "string", format: "binary" };
}
wrapResult(ex: ts.Expression) {
return this.opts?.optimistic ? callOazapftsFunction("ok", [ex]) : ex;
}
formatPathParameter(name: string, parameter?: OpenAPIV3.ParameterObject) {
const schema = parameter?.schema
? this.resolve<SchemaObject>(parameter.schema)
: null;
if (parameter && (schema?.type === "array" || schema?.type === "object")) {
const expression = _.camelCase(name);
const formatter = getFormatter({
style: "simple",
explode: parameter.style === "form",
...parameter,
});
return callQsFunction(
formatter,
formatter === "simple" || formatter === "pipe" || formatter === "space"
? [factory.createIdentifier(expression)]
: [
cg.createObjectLiteral([
[expression, factory.createIdentifier(expression)],
]),
]
);
}
return formatPrimitivePathParameter(name);
}
generateApi() {
this.reset();
// Parse ApiStub.ts so that we don't have to generate everything manually
const stub = cg.parseFile(
path.resolve(__dirname, "../../src/codegen/ApiStub.ts")
);
// ApiStub contains `const servers = {}`, find it ...
const servers = cg.findFirstVariableDeclaration(stub.statements, "servers");
// servers.initializer is readonly, this might break in a future TS version, but works fine for now.
Object.assign(servers, {
initializer: generateServers(this.spec.servers || []),
});
const { initializer } = cg.findFirstVariableDeclaration(
stub.statements,
"defaults"
);
if (!initializer || !ts.isObjectLiteralExpression(initializer)) {
throw new Error("No object literal: defaults");
}
cg.changePropertyValue(
initializer,
"baseUrl",
defaultBaseUrl(this.spec.servers || [])
);
// Collect class functions to be added...
const functions: ts.FunctionDeclaration[] = [];
// Keep track of names to detect duplicates
const names: Record<string, number> = {};
Object.keys(this.spec.paths).forEach((path) => {
const item = this.spec.paths[path];
if (!item) {
return;
}
Object.keys(this.resolve(item)).forEach((verb) => {
const method = verb.toUpperCase();
// skip summary/description/parameters etc...
if (!verbs.includes(method)) return;
const op: OpenAPIV3.OperationObject = (item as any)[verb];
const {
operationId,
requestBody,
responses,
summary,
description,
tags,
} = op;
if (this.skip(tags)) {
return;
}
let name = getOperationName(verb, path, operationId);
const count = (names[name] = (names[name] || 0) + 1);
if (count > 1) {
// The name is already taken, which means that the spec is probably
// invalid as operationIds must be unique. Since this is quite common
// nevertheless we append a counter:
name += count;
}
// merge item and op parameters
const resolvedParameters = [
...this.resolveArray(item.parameters),
...this.resolveArray(op.parameters),
];
// expand older OpenAPI parameters into deepObject style where needed
const parameters = this.isConverted
? supportDeepObjects(resolvedParameters)
: resolvedParameters;
// split into required/optional
const [required, optional] = _.partition(parameters, "required");
// convert parameter names to argument names ...
const argNames: any = {};
parameters
.map((p) => p.name)
.sort((a, b) => a.length - b.length)
.forEach((name) => {
argNames[name] = _.camelCase(name);
});
// build the method signature - first all the required parameters
const methodParams = required.map((p) =>
cg.createParameter(argNames[this.resolve(p).name], {
type: this.getTypeFromSchema(isReference(p) ? p : p.schema),
})
);
let body: any;
let bodyVar;
// add body if present
if (requestBody) {
body = this.resolve(requestBody);
const schema = this.getSchemaFromContent(body.content);
const type = this.getTypeFromSchema(schema);
bodyVar = _.camelCase(
(type as any).name || getReferenceName(schema) || "body"
);
methodParams.push(
cg.createParameter(bodyVar, {
type,
questionToken: !body.required,
})
);
}
// add an object with all optional parameters
if (optional.length) {
methodParams.push(
cg.createParameter(
cg.createObjectBinding(
optional
.map((param) => this.resolve(param))
.map(({ name }) => ({ name: argNames[name] }))
),
{
initializer: factory.createObjectLiteralExpression(),
type: factory.createTypeLiteralNode(
optional.map((p) =>
cg.createPropertySignature({
name: argNames[this.resolve(p).name],
questionToken: true,
type: this.getTypeFromSchema(
isReference(p) ? p : p.schema
),
})
)
),
}
)
);
}
methodParams.push(
cg.createParameter("opts", {
type: factory.createTypeReferenceNode(
"Oazapfts.RequestOpts",
undefined
),
questionToken: true,
})
);
// Next, build the method body...
const returnType = this.getResponseType(responses);
const query = parameters.filter((p) => p.in === "query");
const header = parameters
.filter((p) => p.in === "header")
.map((p) => p.name);
let qs;
if (query.length) {
const paramsByFormatter = _.groupBy(query, getFormatter);
qs = callQsFunction(
"query",
Object.entries(paramsByFormatter).map(([format, params]) => {
//const [allowReserved, encodeReserved] = _.partition(params, "allowReserved");
return callQsFunction(
format === "simple"
? "form"
: format === "pipe"
? "formPipe"
: format === "space"
? "formSpace"
: format,
[
cg.createObjectLiteral(
params.map((p) => [p.name, argNames[p.name]])
),
]
);
})
);
}
const url = createUrlExpression(path, qs, (name) =>
this.formatPathParameter(
name,
parameters.find(
({ name: n, in: loc }) => loc === "path" && n === name
)
)
);
const init: ts.ObjectLiteralElementLike[] = [
factory.createSpreadAssignment(factory.createIdentifier("opts")),
];
if (method !== "GET") {
init.push(
factory.createPropertyAssignment(
"method",
factory.createStringLiteral(method)
)
);
}
if (bodyVar) {
init.push(
cg.createPropertyAssignment(
"body",
factory.createIdentifier(bodyVar)
)
);
}
if (header.length) {
init.push(
factory.createPropertyAssignment(
"headers",
factory.createObjectLiteralExpression(
[
factory.createSpreadAssignment(
factory.createLogicalAnd(
factory.createIdentifier("opts"),
factory.createPropertyAccessExpression(
factory.createIdentifier("opts"),
"headers"
)
)
),
...header.map((name) =>
cg.createPropertyAssignment(
name,
factory.createIdentifier(argNames[name])
)
),
],
true
)
)
);
}
const args: ts.Expression[] = [url];
if (init.length) {
const m = Object.entries(contentTypes).find(([type]) => {
return !!_.get(body, ["content", type]);
});
const initObj = factory.createObjectLiteralExpression(init, true);
args.push(m ? callOazapftsFunction(m[1], [initObj]) : initObj); // json, form, multipart
}
functions.push(
cg.addComment(
cg.createFunctionDeclaration(
name,
{
modifiers: [cg.modifier.export],
},
methodParams,
cg.block(
factory.createReturnStatement(
this.wrapResult(
callOazapftsFunction(
{
json: "fetchJson",
text: "fetchText",
blob: "fetchBlob",
}[returnType],
args,
returnType === "json" || returnType === "blob"
? [
this.getTypeFromResponses(responses!) ||