typescript 从swagger.yaml生成TypeScript接口

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 从swagger.yaml生成TypeScript接口相关的知识,希望对你有一定的参考价值。

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

以上是关于typescript 从swagger.yaml生成TypeScript接口的主要内容,如果未能解决你的问题,请参考以下文章

Python Flask:从 Swagger YAML 到 Google App Engine?

使用 swagger 4.x 包生成 swagger 2.0 yaml

如何从 python 中的嵌套 YAML 文件中读取数据?

Swagger-UI 和 Ktor 如何导入 swagger.json 或 .yaml 文件并启动 Swagger-UI?

2022-02-26:k8s安装swagger,yaml如何写?

如何在 swagger/yaml 文档上正确记录文本/csv 响应?