|
| 1 | +import ts from 'typescript'; |
| 2 | + |
| 3 | +import jsonContent from './swagger.json'; |
| 4 | +import {writeFile} from './fileUtil'; |
| 5 | + |
| 6 | +type PropertiesSchema = Record<string, {type: string} | undefined>; |
| 7 | + |
| 8 | +function mapSwaggerTypeToKeyword(swaggerType: string): number { |
| 9 | + switch (swaggerType) { |
| 10 | + case 'integer': |
| 11 | + case 'number': |
| 12 | + return ts.SyntaxKind.NumberKeyword; |
| 13 | + case 'string': |
| 14 | + return ts.SyntaxKind.StringKeyword; |
| 15 | + default: |
| 16 | + return ts.SyntaxKind.UnknownKeyword; |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +function createDeclaration( |
| 21 | + declarationName: string, |
| 22 | + propertiesSchema: PropertiesSchema, |
| 23 | + requiredProperties: string[] = [] |
| 24 | +): ts.InterfaceDeclaration { |
| 25 | + const mappedProperties = Object.entries(propertiesSchema).map(([propertyName, propertySchema]) => { |
| 26 | + // e.g. SyntaxKind.StringKeyword |
| 27 | + const typeSyntaxKind = mapSwaggerTypeToKeyword(propertySchema!.type); |
| 28 | + |
| 29 | + // e.g. 'string' |
| 30 | + const typeKeyword = ts.createKeywordTypeNode(typeSyntaxKind); |
| 31 | + |
| 32 | + // e.g. '?' |
| 33 | + const questionMarkToken = requiredProperties.includes(propertyName) |
| 34 | + ? undefined |
| 35 | + : ts.createToken(ts.SyntaxKind.QuestionToken); |
| 36 | + |
| 37 | + return ts.createPropertySignature( |
| 38 | + undefined, // readonly? |
| 39 | + propertyName, // property name |
| 40 | + questionMarkToken, // required? |
| 41 | + typeKeyword, // property type |
| 42 | + undefined, // expression, e.g. '++' |
| 43 | + ); |
| 44 | + }); |
| 45 | + |
| 46 | + return ts.createInterfaceDeclaration( |
| 47 | + undefined, // private? |
| 48 | + undefined, // readonly? |
| 49 | + declarationName, // interface name |
| 50 | + undefined, // generics? |
| 51 | + undefined, // extends? |
| 52 | + mappedProperties, // properties |
| 53 | + ); |
| 54 | +} |
| 55 | + |
| 56 | +function saveDeclarations(declarations: ts.InterfaceDeclaration[]): Promise<void> { |
| 57 | + const fileName = 'interfaces-ts.ts'; |
| 58 | + |
| 59 | + const sourceFile = ts.createSourceFile(fileName, '', ts.ScriptTarget.ESNext); |
| 60 | + const sourceCode = declarations |
| 61 | + .map(declaration => ts.createPrinter().printNode(ts.EmitHint.Unspecified, declaration, sourceFile)) |
| 62 | + .join('\n\n'); |
| 63 | + |
| 64 | + return writeFile(fileName, sourceCode); |
| 65 | +} |
| 66 | + |
| 67 | +const declarations = Object.entries(jsonContent.definitions).map(([definitionName, definitionSchema]) => |
| 68 | + createDeclaration(definitionName, definitionSchema.properties, definitionSchema.required) |
| 69 | +); |
| 70 | + |
| 71 | +saveDeclarations(declarations).catch(error => console.error(error)); |
0 commit comments