Skip to content

Instantly share code, notes, and snippets.

@ovrmrw
Created March 23, 2018 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ovrmrw/4ef4710569bfcf67a8b1ed0f10629db7 to your computer and use it in GitHub Desktop.
Save ovrmrw/4ef4710569bfcf67a8b1ed0f10629db7 to your computer and use it in GitHub Desktop.
Generate TypeScript interfaces from swagger.yaml
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());
});
@davvit
Copy link

davvit commented Oct 9, 2020

whats the best way to run this fast during dev.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment