0
# Configuration
1
2
Comprehensive configuration options for customizing the API generation process, including input/output settings, type generation options, naming conventions, and advanced customization hooks.
3
4
## Input/Output Configuration
5
6
### Input Sources
7
8
```typescript { .api }
9
// Local file input
10
interface GenerateApiParamsFromPath {
11
/** Path to local OpenAPI schema file */
12
input: string;
13
// ... other config options
14
}
15
16
// Remote URL input
17
interface GenerateApiParamsFromUrl {
18
/** URL to remote OpenAPI schema */
19
url: string;
20
/** Optional authorization token for private schemas */
21
authorizationToken?: string;
22
/** Request options for schema fetching */
23
requestOptions?: Partial<RequestInit>;
24
// ... other config options
25
}
26
27
// Direct spec object input
28
interface GenerateApiParamsFromSpecLiteral {
29
/** OpenAPI specification object */
30
spec: import("swagger-schema-official").Spec;
31
// ... other config options
32
}
33
```
34
35
### Output Configuration
36
37
```typescript { .api }
38
interface OutputConfig {
39
/** Output directory path or false to skip file writing */
40
output: string | false;
41
/** Generated file name (default: "Api.ts") */
42
fileName: string;
43
/** Clean output directory before generation */
44
cleanOutput: boolean;
45
/** Generate JavaScript with declaration files */
46
toJS: boolean;
47
/** Generate separate files for different components */
48
modular: boolean;
49
}
50
```
51
52
**Usage Examples:**
53
54
```typescript
55
// Write to disk
56
const result = await generateApi({
57
input: "./openapi.json",
58
output: "./src/generated",
59
fileName: "ApiClient.ts",
60
cleanOutput: true
61
});
62
63
// Keep in memory only
64
const result = await generateApi({
65
input: "./openapi.json",
66
output: false // Files available in result.files
67
});
68
69
// Generate JavaScript
70
const result = await generateApi({
71
input: "./openapi.json",
72
output: "./dist",
73
toJS: true,
74
fileName: "ApiClient.js"
75
});
76
```
77
78
## HTTP Client Configuration
79
80
```typescript { .api }
81
interface HttpClientConfig {
82
/** HTTP client type: "fetch" | "axios" */
83
httpClientType: "fetch" | "axios";
84
/** Allow HttpClient instance in API constructor */
85
singleHttpClient: boolean;
86
/** Don't throw errors on non-successful responses */
87
disableThrowOnError: boolean;
88
/** Unwrap data item from response */
89
unwrapResponseData: boolean;
90
}
91
```
92
93
**Usage Examples:**
94
95
```typescript
96
// Fetch client with custom error handling
97
const result = await generateApi({
98
input: "./openapi.json",
99
httpClientType: "fetch",
100
disableThrowOnError: true,
101
unwrapResponseData: true
102
});
103
104
// Axios client with single instance support
105
const result = await generateApi({
106
input: "./openapi.json",
107
httpClientType: "axios",
108
singleHttpClient: true
109
});
110
```
111
112
## Generation Options
113
114
### Core Generation Flags
115
116
```typescript { .api }
117
interface GenerationFlags {
118
/** Generate API client class */
119
generateClient: boolean;
120
/** Generate response type definitions */
121
generateResponses: boolean;
122
/** Generate route type definitions */
123
generateRouteTypes: boolean;
124
/** Use "default" response as success response */
125
defaultResponseAsSuccess: boolean;
126
/** Default type for empty response schemas */
127
defaultResponseType: string;
128
}
129
```
130
131
### Type Generation Options
132
133
```typescript { .api }
134
interface TypeGenerationConfig {
135
/** Generate readonly properties */
136
addReadonly: boolean;
137
/** Use Array<Type> instead of Type[] */
138
anotherArrayType: boolean;
139
/** Generate union enums (T1 | T2) instead of enum construct */
140
generateUnionEnums: boolean;
141
/** Use x-enumNames as enum values */
142
enumNamesAsValues: boolean;
143
}
144
```
145
146
### Extraction Options
147
148
```typescript { .api }
149
interface ExtractionConfig {
150
/** Extract request body types to data contracts */
151
extractRequestBody: boolean;
152
/** Extract response body types to data contracts */
153
extractResponseBody: boolean;
154
/** Extract response error types to data contracts */
155
extractResponseError: boolean;
156
/** Extract request parameters to data contracts */
157
extractRequestParams: boolean;
158
/** Extract all enums to TypeScript enum construction */
159
extractEnums: boolean;
160
/** Extract all responses from /components/responses */
161
extractResponses: boolean;
162
}
163
```
164
165
**Usage Examples:**
166
167
```typescript
168
// Full type extraction
169
const result = await generateApi({
170
input: "./openapi.json",
171
extractRequestBody: true,
172
extractResponseBody: true,
173
extractResponseError: true,
174
extractEnums: true,
175
addReadonly: true
176
});
177
178
// Union types instead of enums
179
const result = await generateApi({
180
input: "./openapi.json",
181
generateUnionEnums: true,
182
enumNamesAsValues: true
183
});
184
```
185
186
## Naming and Organization
187
188
### Naming Configuration
189
190
```typescript { .api }
191
interface NamingConfig {
192
/** Name of the main API class */
193
apiClassName: string;
194
/** Prefix for generated type names */
195
typePrefix: string;
196
/** Suffix for generated type names */
197
typeSuffix: string;
198
/** Prefix for enum keys */
199
enumKeyPrefix: string;
200
/** Suffix for enum keys */
201
enumKeySuffix: string;
202
/** Prefix for invalid type names */
203
fixInvalidTypeNamePrefix: string;
204
/** Prefix for invalid enum keys */
205
fixInvalidEnumKeyPrefix: string;
206
}
207
```
208
209
### Organization Options
210
211
```typescript { .api }
212
interface OrganizationConfig {
213
/** Path index for route module separation */
214
moduleNameIndex: number;
215
/** Use first tag for module names */
216
moduleNameFirstTag: boolean;
217
/** Sort data contracts alphabetically */
218
sortTypes: boolean;
219
/** Sort routes alphabetically */
220
sortRoutes: boolean;
221
}
222
```
223
224
**Usage Examples:**
225
226
```typescript
227
// Custom naming
228
const result = await generateApi({
229
input: "./openapi.json",
230
apiClassName: "MyApiClient",
231
typePrefix: "API",
232
typeSuffix: "DTO",
233
sortTypes: true,
234
sortRoutes: true
235
});
236
237
// Module organization
238
const result = await generateApi({
239
input: "./openapi.json",
240
moduleNameFirstTag: true,
241
moduleNameIndex: 1,
242
modular: true
243
});
244
```
245
246
## Template Configuration
247
248
### Template Paths
249
250
```typescript { .api }
251
interface TemplateConfig {
252
/** Path to custom templates directory */
253
templates: string;
254
/** Template file paths */
255
templatePaths: {
256
base: string;
257
default: string;
258
modular: string;
259
original: string;
260
custom: string | null;
261
};
262
}
263
```
264
265
### Template Generation Options
266
267
```typescript { .api }
268
interface GenerateTemplatesParams {
269
/** Clean output folder before generation */
270
cleanOutput?: boolean;
271
/** Output directory for templates */
272
output?: string;
273
/** HTTP client type for templates */
274
httpClientType?: HttpClientType;
275
/** Generate modular template structure */
276
modular?: boolean;
277
/** Overwrite existing templates */
278
rewrite?: boolean;
279
/** Suppress output messages */
280
silent?: boolean;
281
/** Enable debug output */
282
debug?: boolean;
283
}
284
```
285
286
**Usage Examples:**
287
288
```typescript
289
// Custom templates
290
const result = await generateApi({
291
input: "./openapi.json",
292
templates: "./my-custom-templates"
293
});
294
295
// Generate custom templates
296
const templates = await generateTemplates({
297
output: "./templates",
298
httpClientType: "axios",
299
modular: true,
300
cleanOutput: true
301
});
302
```
303
304
## Advanced Customization
305
306
### Lifecycle Hooks
307
308
Hooks provide powerful customization points throughout the generation process:
309
310
```typescript { .api }
311
const result = await generateApi({
312
input: "./openapi.json",
313
hooks: {
314
// Customize initialization
315
onInit: (config, codeGenProcess) => {
316
console.log("Starting generation with config:", config.fileName);
317
return config;
318
},
319
320
// Customize route processing
321
onCreateRoute: (routeData) => {
322
// Skip certain routes
323
if (routeData.raw.tags?.includes("internal")) {
324
return false; // Skip this route
325
}
326
327
// Modify route names
328
routeData.routeName.usage = routeData.routeName.usage.replace(/Api$/, "Service");
329
return routeData;
330
},
331
332
// Customize type names
333
onFormatTypeName: (typeName, rawTypeName, schemaType) => {
334
if (schemaType === "type-name") {
335
return typeName.endsWith("DTO") ? typeName : `${typeName}DTO`;
336
}
337
return typeName;
338
},
339
340
// Customize route names
341
onFormatRouteName: (routeInfo, templateRouteName) => {
342
return `${routeInfo.method.toLowerCase()}${templateRouteName}`;
343
},
344
345
// Customize schema parsing
346
onParseSchema: (originalSchema, parsedSchema) => {
347
// Add custom properties or modify parsed result
348
return parsedSchema;
349
},
350
351
// Customize components
352
onCreateComponent: (component) => {
353
// Modify component before processing
354
return component;
355
}
356
}
357
});
358
```
359
360
### Type Construction Customization
361
362
```typescript { .api }
363
const result = await generateApi({
364
input: "./openapi.json",
365
// Customize primitive type mappings
366
primitiveTypeConstructs: (struct) => ({
367
...struct,
368
string: {
369
...struct.string,
370
'date-time': () => 'Date', // Map date-time to Date instead of string
371
'uuid': () => 'string',
372
'email': () => 'string'
373
},
374
integer: () => 'number',
375
number: () => 'number'
376
}),
377
378
// Customize code generation constructs
379
codeGenConstructs: (struct) => ({
380
...struct,
381
Keyword: {
382
...struct.Keyword,
383
Any: 'unknown' // Use unknown instead of any
384
},
385
ArrayType: (content) => `ReadonlyArray<${content}>` // Make arrays readonly
386
})
387
});
388
```
389
390
### Schema Parser Customization
391
392
```typescript { .api }
393
const result = await generateApi({
394
input: "./openapi.json",
395
schemaParsers: {
396
// Custom enum parser
397
enum: (schemaParserInput) => {
398
// Custom enum parsing logic
399
return customEnumParser(schemaParserInput);
400
},
401
402
// Custom object parser
403
object: (schemaParserInput) => {
404
// Custom object parsing logic
405
return customObjectParser(schemaParserInput);
406
}
407
}
408
});
409
```
410
411
### Extraction Customization
412
413
```typescript { .api }
414
const result = await generateApi({
415
input: "./openapi.json",
416
extractingOptions: {
417
// Custom suffixes for extracted types
418
requestBodySuffix: ["Request", "Input", "Payload"],
419
responseBodySuffix: ["Response", "Output", "Result"],
420
responseErrorSuffix: ["Error", "ErrorResponse"],
421
enumSuffix: ["Enum", "Type"],
422
423
// Custom name resolvers
424
requestBodyNameResolver: (name, reservedNames) => {
425
return `${name}RequestBody`;
426
},
427
responseBodyNameResolver: (name, reservedNames) => {
428
return `${name}ResponseBody`;
429
},
430
enumNameResolver: (name, reservedNames) => {
431
return `${name}Enum`;
432
}
433
}
434
});
435
```
436
437
## Debug and Development Options
438
439
```typescript { .api }
440
interface DebugConfig {
441
/** Enable debug output */
442
debug: boolean;
443
/** Suppress all output except errors */
444
silent: boolean;
445
/** Fix small errors in swagger schema */
446
patch: boolean;
447
}
448
```
449
450
**Usage Examples:**
451
452
```typescript
453
// Debug mode
454
const result = await generateApi({
455
input: "./openapi.json",
456
debug: true,
457
patch: true
458
});
459
460
// Silent mode
461
const result = await generateApi({
462
input: "./openapi.json",
463
silent: true
464
});
465
```
466
467
## Configuration File
468
469
For complex configurations, create a dedicated configuration file:
470
471
```typescript
472
// swagger-typescript-api.config.js
473
export default {
474
httpClientType: "axios",
475
generateResponses: true,
476
generateRouteTypes: true,
477
extractEnums: true,
478
sortTypes: true,
479
apiClassName: "ApiClient",
480
typePrefix: "API",
481
hooks: {
482
onFormatTypeName: (typeName) => {
483
return typeName.replace(/^API/, '').replace(/DTO$/, '');
484
},
485
onCreateRoute: (routeData) => {
486
// Skip deprecated routes
487
if (routeData.raw.deprecated) {
488
return false;
489
}
490
return routeData;
491
}
492
},
493
primitiveTypeConstructs: (struct) => ({
494
...struct,
495
string: {
496
...struct.string,
497
'date-time': () => 'Date',
498
'date': () => 'Date'
499
}
500
})
501
};
502
```
503
504
Then use it in your generation:
505
506
```typescript
507
import config from "./swagger-typescript-api.config.js";
508
509
const result = await generateApi({
510
input: "./openapi.json",
511
...config
512
});
513
```
514
515
## Default Values
516
517
```typescript { .api }
518
const DEFAULT_CONFIG = {
519
// Output
520
fileName: "Api.ts",
521
output: "./",
522
cleanOutput: false,
523
524
// Generation
525
generateClient: true,
526
generateResponses: false,
527
generateRouteTypes: false,
528
generateUnionEnums: false,
529
530
// HTTP Client
531
httpClientType: "fetch",
532
singleHttpClient: false,
533
disableThrowOnError: false,
534
535
// Types
536
addReadonly: false,
537
anotherArrayType: false,
538
extractEnums: false,
539
540
// Naming
541
apiClassName: "Api",
542
typePrefix: "",
543
typeSuffix: "",
544
545
// Processing
546
defaultResponseAsSuccess: false,
547
defaultResponseType: "void",
548
patch: false,
549
550
// Organization
551
moduleNameIndex: 0,
552
moduleNameFirstTag: false,
553
sortTypes: false,
554
sortRoutes: false,
555
556
// Debug
557
debug: false,
558
silent: false
559
};
560
```