https://github.com/charlzyx/apicast
https://github.com/charlzyx/apicast
Last synced: 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/charlzyx/apicast
- Owner: charlzyx
- Created: 2023-05-16T09:40:19.000Z (about 2 years ago)
- Default Branch: master
- Last Pushed: 2023-05-17T11:12:23.000Z (about 2 years ago)
- Last Synced: 2025-02-11T17:16:03.467Z (4 months ago)
- Language: TypeScript
- Size: 15.6 KB
- Stars: 0
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# apicast
将给定的 Swagger/OpenAPIV3 转换为类型和请求文件
## install
```bash
yarn add apicast
```## usage
```
npx apicast
```## 配置文件
apicast.config.ts
```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