Created
March 23, 2018 02:24
-
-
Save ovrmrw/4ef4710569bfcf67a8b1ed0f10629db7 to your computer and use it in GitHub Desktop.
Generate TypeScript interfaces from swagger.yaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as jsyaml from 'js-yaml'; | |
import * as path from 'path'; | |
import * as fs from 'fs'; | |
interface PropertyStructure { | |
required: string[]; | |
properties: Record<string, { type: string }>; | |
} | |
class Definition { | |
constructor(private name: string, private property: PropertyStructure) {} | |
generateInterface(): string { | |
const lines: string[] = []; | |
lines.push(`export interface ${this.name} {`); | |
Object.keys(this.property.properties).forEach(name => { | |
const required: boolean = this.property.required.includes(name); | |
const type: string = this.property.properties[name].type; | |
lines.push(` ${name}${required ? '' : '?'}: ${type};`); | |
}); | |
lines.push('}'); | |
return lines.join('\n'); | |
} | |
} | |
const root = path.resolve(); | |
const swaggerYaml = path.join(root, 'api/swagger/swagger.yaml'); | |
const yaml = jsyaml.safeLoad(fs.readFileSync(swaggerYaml).toString()); | |
console.log(yaml); | |
Object.entries(yaml.definitions).forEach(([name, property]) => { | |
console.log(name, JSON.stringify(property), '\n↓'); | |
const definition = new Definition(name, property as any); | |
console.log(definition.generateInterface()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
whats the best way to run this fast during dev.