@aplus-frontend/api-generator
v1.0.1
Published
APlus API code generator from OpenAPI documentation
Readme
@aplus-frontend/api-generator
从 OpenAPI 文档生成 TypeScript 接口代码的工具,支持 CLI 和 API两种使用方式。
安装
pnpm add @aplus-frontend/api-generatorCLI 使用
初始化配置
在项目根目录下创建 api-generate.json 和 api-doc.json 配置文件:
npx aplus-gen init生成代码
# 使用内置模板
npx aplus-gen generate
# 指定项目目录
npx aplus-gen generate --dir /path/to/project
# 使用自定义模板
npx aplus-gen generate --template /path/to/templatesAPI 使用
import { generate, initConfig, getBuiltinTemplateDir } from '@aplus-frontend/api-generator';
// 初始化配置
await initConfig({
workspaceRoot: '/path/to/project',
});
// 生成代码
const result = await generate({
workspaceRoot: '/path/to/project',
templateDir: getBuiltinTemplateDir(),
});
if (result.success) {
console.log('生成成功:', result.indexPath, result.interfacePath);
} else {
console.error('生成失败:', result.error);
}配置说明
api-generate.json
{
"apiPath": "src/api",
"serviceName": "/api/v1",
"defPath": "@/utils/http",
"hooks": true
}| 字段 | 类型 | 说明 |
|------|------|------|
| apiPath | string | API 文件存放路径 |
| serviceName | string | 服务路径前缀 |
| defPath | string | HTTP 工具导入路径 |
| hooks | boolean | 是否生成 vue-request hooks |
api-doc.json
OpenAPI/Swagger JSON 文档内容。
生成的文件结构
src/api/
├── index.ts # 接口函数
└── interface.ts # TypeScript 类型定义自定义模板
模板使用 Nunjucks 语法,包含以下模板文件:
interface.njk- 类型定义模板service.njk- 接口函数模板
自定义模板时,保持相同的变量结构即可。
高级用法
自定义文件系统
import type { FileSystem } from '@aplus-frontend/api-generator';
class CustomFileSystem implements FileSystem {
async readFile(filePath: string): Promise<string> { /* ... */ }
async writeFile(filePath: string, content: string): Promise<void> { /* ... */ }
async stat(filePath: string) { /* ... */ }
async mkdir(dirPath: string, options?: { recursive: boolean }): Promise<void> { /* ... */ }
async exists(filePath: string): Promise<boolean> { /* ... */ }
}
const result = await generate({
workspaceRoot: '/path/to/project',
templateDir: getBuiltinTemplateDir(),
fs: new CustomFileSystem(),
});自定义消息处理
import type { MessageHandler } from '@aplus-frontend/api-generator';
const result = await generate({
workspaceRoot: '/path/to/project',
templateDir: getBuiltinTemplateDir(),
messageHandler: {
info: (msg) => console.log('[INFO]', msg),
error: (msg) => console.error('[ERROR]', msg),
warn: (msg) => console.warn('[WARN]', msg),
},
});License
MIT
