tom-sapletta-com
12/14/2018 - 8:10 PM

Generate TypeScript interfaces from swagger.yaml

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());
});