|
1 | 1 | /* eslint-disable no-console */
|
2 | 2 | import fs from 'node:fs';
|
3 | 3 |
|
4 |
| -import openapiTS from 'openapi-typescript'; |
| 4 | +import openapiTS, { astToString } from 'openapi-typescript'; |
| 5 | +import ts from 'typescript'; |
5 | 6 |
|
6 | 7 | const OPENAPI_URL = 'http://127.0.0.1:9090/openapi.json';
|
7 | 8 | const OUTPUT_FILE = 'src/services/api/schema.ts';
|
8 | 9 |
|
9 | 10 | async function generateTypes(schema) {
|
10 | 11 | process.stdout.write(`Generating types ${OUTPUT_FILE}...`);
|
| 12 | + |
| 13 | + // Use https://ts-ast-viewer.com to figure out how to create these AST nodes - define a type and use the bottom-left pane's output |
| 14 | + // `Blob` type |
| 15 | + const BLOB = ts.factory.createTypeReferenceNode(ts.factory.createIdentifier('Blob')); |
| 16 | + // `null` type |
| 17 | + const NULL = ts.factory.createLiteralTypeNode(ts.factory.createNull()); |
| 18 | + // `Record<string, unknown>` type |
| 19 | + const RECORD_STRING_UNKNOWN = ts.factory.createTypeReferenceNode(ts.factory.createIdentifier('Record'), [ |
| 20 | + ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), |
| 21 | + ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword), |
| 22 | + ]); |
| 23 | + |
11 | 24 | const types = await openapiTS(schema, {
|
12 | 25 | exportType: true,
|
13 | 26 | transform: (schemaObject) => {
|
14 | 27 | if ('format' in schemaObject && schemaObject.format === 'binary') {
|
15 |
| - return schemaObject.nullable ? 'Blob | null' : 'Blob'; |
| 28 | + return schemaObject.nullable ? ts.factory.createUnionTypeNode([BLOB, NULL]) : BLOB; |
16 | 29 | }
|
17 | 30 | if (schemaObject.title === 'MetadataField') {
|
18 | 31 | // This is `Record<string, never>` by default, but it actually accepts any a dict of any valid JSON value.
|
19 |
| - return 'Record<string, unknown>'; |
| 32 | + return RECORD_STRING_UNKNOWN; |
20 | 33 | }
|
21 | 34 | },
|
| 35 | + defaultNonNullable: false, |
22 | 36 | });
|
23 |
| - fs.writeFileSync(OUTPUT_FILE, types); |
| 37 | + fs.writeFileSync(OUTPUT_FILE, astToString(types)); |
24 | 38 | process.stdout.write(`\nOK!\r\n`);
|
25 | 39 | }
|
26 | 40 |
|
|
0 commit comments