npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@magicbe/api-generator

v0.1.10

Published

api 生成器

Readme

@magicbe/api-generator

一个强大的 API 代码生成器,支持从 YApi 和 Swagger 自动生成 TypeScript/JavaScript 接口定义和请求函数。

✨ 核心特性

  • 🚀 多平台支持: 支持 YApi 和 Swagger/OpenAPI 两大主流 API 管理平台
  • 🔒 类型安全: 自动生成完整的 TypeScript 接口定义,确保类型安全
  • 🎯 智能命名: 自动处理接口命名,支持驼峰命名转换和特殊字符处理
  • 📦 嵌套接口: 智能生成嵌套接口,保持代码结构清晰
  • 🔧 特殊字符处理: 正确处理以数字开头的属性名(使用引号包裹)
  • 📋 代码格式化: 使用 Prettier 自动格式化生成的代码
  • ⚙️ 灵活配置: 支持配置文件和命令行参数两种方式
  • 📖 帮助系统: 内置完整的帮助文档 (--help / -h)

🚀 快速开始

安装

# 全局安装
npm install -g @magicbe/api-generator
# 或
yarn global add @magicbe/api-generator
# 或
pnpm add -g @magicbe/api-generator

基本使用

方法 1: 使用配置文件

创建 api-generator.config.json 文件:

{
  "type": "yapi",
  "service": "https://your-yapi-domain.com",
  "token": "your-api-token",
  "output": "./src/api",
  "target": "typescript"
}

运行命令:

gen-api

方法 2: 使用命令行参数

gen-api --type yapi --service https://your-yapi-domain.com --token your-api-token --output ./src/api --target typescript

方法 3: 查看帮助

gen-api --help
# 或
gen-api -h

📋 配置参数

命令行参数

| 参数 | 类型 | 说明 | 必填 | |------|------|------|------| | --type | string | API 平台类型: yapi | swagger | ✅ | | --service | string | API 服务地址 | ✅ | | --output | string | 输出目录路径 | ✅ | | --target | string | 目标语言: typescript | javascript | ✅ | | --token | string | YApi 访问令牌 (YApi 需要) | ❌ | | --cats | string | YApi 分类 ID,多个用逗号分隔 (YApi 可选) | ❌ | | --resources | string | Swagger 资源名称,多个用逗号分隔 (Swagger 可选) | ❌ | | --function | string | 请求函数导入路径 (可选,默认: @/request) | ❌ | | --headers | string | 自定义请求头,JSON 格式 (Swagger 可选) | ❌ | | --config | string | 配置文件路径 (可选,默认: ./api-generator.config.json) | ❌ | | --help, -h | - | 显示帮助信息 | ❌ |

配置文件格式

{
  "type": "yapi",
  "service": "https://your-yapi-domain.com",
  "token": "your-api-token",
  "output": "./src/api",
  "target": "typescript",
  "function": "@/utils/request",
  "cats": [123, 456],
}

🏗️ 生成的代码结构

接口定义示例

/** 用户列表 请求参数 */
export interface GetUserListQuery {
  page: number;
  page_size: number;
  keyword?: string;
}

/** 用户列表 响应数据 */
export interface GetUserListResponseData {
  total: number;
  items: GetUserListResponseDataItems[];
}

/** 用户列表 响应主体 */
export interface GetUserListResponse {
  code: number;
  msg: string;
  data: GetUserListResponseData;
}

请求函数示例

/**
 * 用户列表
 * https://yapi.example.com/project/123/interface/api/456
 */
export const getUserList = (query: GetUserListQuery) => 
  request.get<GetUserListResponse>('/user/list', { params: query });

🎯 智能特性详解

1. 智能接口命名

  • 路径转换: 自动将 API 路径转换为驼峰命名
  • HTTP 方法前缀: 根据请求方法添加前缀 (get, post, put, delete)
  • 参数处理: 智能处理路径参数和查询参数

2. 嵌套接口生成

  • 层次结构: 自动识别嵌套对象结构
  • 命名规则: 使用 "当前接口名 + Key(首字母大写)" 的命名方式
  • 递归处理: 支持多层嵌套结构的递归生成

3. 特殊字符处理

  • 数字开头属性: 自动使用引号包裹 (如 "0558d78b39cf4824b57b56047a8d47fc": string)
  • 命名转换: 支持下划线、连字符等转换为驼峰命名
  • 语法合规: 确保生成的 TypeScript 代码完全符合语法规范

4. 类型安全增强

  • 完整类型定义: 为所有接口生成完整的 TypeScript 类型
  • 可选/必填区分: 正确识别可选参数和必填参数
  • 响应数据类型: 为响应数据提供完整的类型约束

📦 项目集成

1. 安装依赖

npm install axios

2. 配置请求实例

创建 src/request.ts

import axios from 'axios';

const request = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 10000,
});

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 添加认证头等逻辑
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    // 统一错误处理
    return Promise.reject(error);
  }
);

export default request;

3. 使用生成的 API

import { getUserList } from '@/api/gen_api_123';

// 使用 API
const loadUsers = async () => {
  try {
    const response = await getUserList({
      page: 1,
      page_size: 10,
      keyword: 'search'
    });
    console.log(response.data);
  } catch (error) {
    console.error('加载用户列表失败:', error);
  }
};

🔧 高级用法

YApi 分类过滤

只生成指定分类的 API:

gen-api --type yapi --service https://yapi.example.com --token your-token --output ./src/api --target typescript --cats 123,456

Swagger 多资源

同时处理多个 Swagger 资源:

gen-api --type swagger --service https://swagger.example.com/swagger.json --output ./src/api --target typescript --resources user,order

自定义函数命名

gen-api --type yapi --service https://yapi.example.com --token your-token --output ./src/api --target typescript --function @/utils/custom-request

🛠️ 开发指南

本地开发

# 克隆项目
git clone https://github.com/your-org/api-generator.git

# 安装依赖
pnpm install

# 开发模式
pnpm dev

# 构建项目
pnpm build

项目结构

src/
├── Generator.ts              # 基础生成器类
├── GeneratorYapi.ts          # YApi 生成器基类
├── GeneratorSwaggerApi.ts    # Swagger 生成器
├── library.ts                # 命令行工具入口
├── help.txt                  # 帮助文档
└── index.ts                  # 主入口文件

构建脚本

  • pnpm dev: 使用 nodemon 进行开发
  • pnpm build: 构建 TypeScript 项目并复制帮助文件
  • pnpm lint: ESLint 代码检查

🎨 代码示例

生成的复杂接口示例

/** 报表详情 响应数据 */
export interface GetAdminReportDetailResponse {
  code: number;
  msg: string;
  data: GetAdminReportDetailResponseData;
}

/** 报表详情 数据内容 */
export interface GetAdminReportDetailResponseData {
  period_map: GetAdminReportDetailResponsePeriodMap;
  total_count: number;
  items: GetAdminReportDetailResponseDataItems[];
}

/** 报表详情 时间段映射 */
export interface GetAdminReportDetailResponsePeriodMap {
  [key: string]: string;
}

/** 报表详情 项目列表 */
export interface GetAdminReportDetailResponseDataItems {
  id: number;
  name: string;
  status: number;
  "0558d78b39cf4824b57b56047a8d47fc": string; // 特殊字符处理示例
}

生成的请求函数示例

/**
 * 获取报表详情
 * https://yapi.example.com/project/123/interface/api/789
 */
export const getAdminReportDetail = (query: GetAdminReportDetailQuery) => 
  request.get<GetAdminReportDetailResponse>('/admin/report/detail', { params: query });

🤝 贡献指南

欢迎提交 Issue 和 Pull Request!

提交规范

  • 使用清晰的提交信息
  • 添加适当的测试用例
  • 更新相关文档
  • 遵循代码风格规范

📄 许可证

MIT License

🆘 支持与联系

如有问题,请通过以下方式联系:


🎉 Happy Coding!

如果你觉得这个项目有帮助,请给个 ⭐️ 支持一下!