apicast
TypeScript icon, indicating that this package has built-in type declarations

1.0.5 • Public • Published

apicast

将给定的 Swagger/OpenAPIV3 转换为类型和请求文件

install

yarn add apicast

usage

npx apicast

配置文件

apicast.config.ts

import type { SwaggerV2 } from "apicast";
import { byTags, defineConfig, makeNameByUrl, typingsOf, where } from "apicast";

export default defineConfig({
  input: {
    swagger: "./swagger.json",
  },
  output: "./api",
  tpl: async (input: SwaggerV2, srouceName: string) => {
    // 根据 tag 分组
    const tags = byTags(input);
    const pickRspType = typingsOf.pickRsp;
    const lines = [
      // 导入类型
      `import { paths } from './${srouceName}DTS';`,
      // 导入辅助函数
      pickRspType,
    ];

    tags.forEach(tag => {
      // 没有方法就不生成
      if (tag.operations.length === 0) return;
      // 描述写入注释
      if (tag.description) {
        lines.push(`\n/** ${tag.description || ""} */`);
      }
      // 导出 tag 对应的模块
      lines.push(`\nexport const ${tag.key} = {`);
      tag.operations.forEach(op => {
        // 拼装单个 请求的代码
        const { method, path } = op;
        const parameterIn = where(op);

        const dataType = [
          parameterIn.query ? `${typingsOf(path, method).query},` : "",
          parameterIn.body ? `${typingsOf(path, method).body},` : "",
          parameterIn.formData ? `${typingsOf(path, method).formData},` : "",
        ].filter(Boolean).join("");

        const fn = [
          "\n",
          op.summary || op.description
            ? `/** ${op.summary || ""} ${op.description || ""} */`
            : "",
          "\n",
          `${makeNameByUrl(path, method)}(`,
          dataType ? `data: ${dataType}` : "",
          `): Promise<${typingsOf(path, method).maybeRsp}> {`,
          `return fetch("${path}", {
              method: "${method}",
               ${
            parameterIn.body || parameterIn.formData
              ? "body: JSON.stringify(data)"
              : ""
          }
            }).then(data => data as any)
          },`,
          "\n",
        ].join("");

        lines.push(fn);
      });
      lines.push(`}\n`);
    });

    return lines.join("\n").replace(/\n\n+/g, "\n");
  },
});

usage

Readme

Keywords

none

Package Sidebar

Install

npm i apicast

Weekly Downloads

0

Version

1.0.5

License

ISC

Unpacked Size

14.1 kB

Total Files

10

Last publish

Collaborators

  • charlzyx