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

@lonely9/api-generate

v0.2.2

Published

通过swagger/openApi的数据生成对应的接口文件。

Readme

api-generate

通过 Swagger/OpenAPI 数据自动生成 TypeScript API 代码的工具库。

注意事项

  • unplugin-dts 目前版本存在问题,如果 typescript 版本为 6.x 及以上则会导致如果设置 bundleTypes: true 会导致合并出来的声明文件为空,建议使用 5.x 版本

✨ 特性

  • 🚀 自动解析 - 支持 Swagger 2.0 和 OpenAPI 3.0
  • 📝 类型安全 - 自动生成 TypeScript 类型定义
  • 🎯 智能生成 - 跳过简单类型(string/number/boolean),只生成复杂接口
  • 📁 灵活配置 - 可配置目录深度、命名规则等
  • 🔄 完整解析 - 深度解析所有 $ref 引用
  • 👤 作者提取 - 自动从 Swagger 提取作者信息
  • ⚙️ 配置文件 - 支持配置文件和命令行参数

📦 安装

npm install @lonely9/api-generate
# or
yarn add @lonely9/api-generate
# or
pnpm add @lonely9/api-generate

🚀 快速开始

基础用法

import { generate } from "@lonely9/api-generate";

// 从文件路径生成
await generate({
  input: "./swagger.json",
  outputDir: "./src/api",
  depth: 2,
});

从 JSON 对象生成

import { generate } from "@lonely9/api-generate";

const swaggerJson = {
  openapi: "3.0.0",
  info: { title: "My API", version: "1.0.0" },
  paths: {
    "/user/list": {
      get: {
        operationId: "getUserList",
        responses: {
          "200": {
            content: {
              "application/json": {
                schema: {
                  type: "object",
                  properties: {
                    list: { type: "array", items: { type: "object" } },
                    total: { type: "number" },
                  },
                },
              },
            },
          },
        },
      },
    },
  },
};

await generate({
  input: swaggerJson,
  outputDir: "./src/api",
});

生成扁平文件结构

import { generate } from "@lonely9/api-generate";

// generateDir: false - 生成扁平文件结构
// 例如: mgmt-user.ts, mgmt-user.types.ts
await generate({
  input: "./swagger.json",
  outputDir: "./src/api",
  depth: 2,
  generateDir: false, // 默认为 false
});

生成嵌套目录结构

import { generate } from "@lonely9/api-generate";

// generateDir: true - 生成嵌套目录结构
// 例如: mgmt/user/index.ts, mgmt/user/types.ts
await generate({
  input: "./swagger.json",
  outputDir: "./src/api",
  depth: 2,
  generateDir: true,
});

返回 zip 文件

import { generate } from "@lonely9/api-generate";
import fs from "fs-extra";

// 不提供 outputDir - 返回 zip Buffer
const zipBuffer = await generate({
  input: "./swagger.json",
  depth: 2,
});

// 保存 zip 文件
await fs.writeFile("api-code.zip", zipBuffer);

📖 API 文档

generate(options: IGenerateOptions): Promise<void | Buffer>

生成 API 代码的主函数。

  • 如果提供了 outputDir,则生成文件到指定目录,返回 Promise<void>
  • 如果没有提供 outputDir,则返回 zip Buffer,返回 Promise<Buffer>

参数选项

interface IGenerateOptions {
  /**
   * Swagger/OpenAPI JSON 数据或文件路径(必填)
   */
  input: string | object;

  /**
   * 输出目录
   * @description 如果不提供 outputDir,则返回 zip Buffer
   */
  outputDir?: string;

  /**
   * 是否生成目录结构
   * @default false
   * @description
   * - true: 按照 depth 生成目录结构,如 mgmt/user/index.ts
   * - false: 扁平文件结构,如 mgmt-user.ts
   */
  generateDir?: boolean;

  /**
   * 目录深度
   * @default 2
   * @example
   * depth=0: 所有 API 在根目录
   * depth=2: /admin/user/list -> admin/user/
   */
  depth?: number;

  /**
   * 作者名称(作为默认值,优先使用 Swagger 中的 x-author 或 info.contact.name)
   */
  author?: string;

  /**
   * 请求库导入路径
   * @default '@/utils/request'
   */
  importPath?: string;

  /**
   * 函数名后缀
   * @default 'Api'
   */
  functionSuffix?: string;

  /**
   * 是否覆盖已存在的文件
   * @default true
   */
  overwrite?: boolean;

  /**
   * 是否在生成前清空输出目录
   * @default true
   */
  clean?: boolean;

  /**
   * 日期格式
   * @default 'YYYY-MM-DD'
   */
  dateFormat?: string;

  /**
   * 是否执行格式化(eslint + prettier)
   * @default false
   */
  format?: boolean;

  /**
   * 是否静默模式(不输出日志)
   * @default false
   */
  silent?: boolean;
}

导出的类型

export type {
  IApiInfo, // API 信息接口
  IConfig, // 配置接口
  IGenerateOptions, // 生成选项接口
  IParameter, // 参数接口
  IParsedData, // 解析结果接口
};

📝 生成示例

输入(Swagger)

{
  "paths": {
    "/user/list": {
      "get": {
        "operationId": "getUserList",
        "summary": "获取用户列表",
        "x-author": "张三",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "list": {
                      "type": "array",
                      "items": { "type": "object" }
                    },
                    "total": { "type": "number" }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/user/{id}": {
      "delete": {
        "operationId": "deleteUser",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": { "type": "string" }
              }
            }
          }
        }
      }
    }
  }
}

输出(user/index.ts)

import type { IGetUserListRes } from "./types";
import { get, del } from "@/utils/request";

/**
 * 获取用户列表
 * @author 张三
 * @date 2026-04-17
 */
export const getUserListApi = () => {
  return get<IGetUserListRes>("/user/list");
};

/**
 * @date 2026-04-17
 * @param id
 */
export const deleteUserApi = (id: string) => {
  return del<string>(`/user/${id}`);
};

输出(user/types.ts)

export interface IGetUserListRes {
  list: any[];
  total: number;
}

// 注意:简单类型 string 不会生成接口,直接使用 string

🎯 命名规范

函数命名

  • GET 请求: get[OperationId]Api
    • 例如:getUserListApi
  • 其他请求: [operationId]Api
    • 例如:createUserApi, updateUserApi
  • 严格驼峰: 移除所有下划线和短横线
    • get_user_listgetUserListApi
  • 重复处理: 自动添加数字后缀
    • getUserApi, getUserApi2

类型命名

  • 请求类型: I[ApiName]Req
  • 响应类型: I[ApiName]Res

简单类型处理

简单类型(stringnumberbooleannull)不生成接口定义,直接使用基本类型:

// ✅ 不会生成这样的冗余类型
// export type IDeleteUserRes = string;

// ✅ 而是直接使用
export const deleteUserApi = () => {
  return del<string>("/user/delete");
};

⚙️ 配置文件

支持在项目根目录创建配置文件,CLI 参数会覆盖配置文件:

支持的文件名:

  • .apirc
  • .apirc.json
  • .apirc.js
  • api-generate.config.js
  • 或在 package.json 中添加 api-generate 字段

示例(.apirc.json):

{
  "outputDir": "./src/services",
  "depth": 2,
  "importPath": "@/services/http",
  "author": "Frontend Team",
  "dateFormat": "YYYY-MM-DD HH:mm:ss",
  "clean": true,
  "overwrite": true
}

📂 目录结构示例

depth=0(所有 API 在根目录)

src/api/
├── index.ts
└── types.ts

depth=2(按路径前 2 层分组)

src/api/
├── admin/
│   ├── system/
│   │   ├── index.ts
│   │   └── types.ts
│   └── user/
│       ├── index.ts
│       └── types.ts
└── auth/
    └── wework/
        ├── index.ts
        └── types.ts

自定义请求方法映射

生成的代码使用以下方法:

  • GETget(url, { params })
  • POSTpost(url, data)
  • PUTput(url, data)
  • DELETEdel(url, { params })
  • PATCHpatch(url, data)

路径参数处理

路径中的参数会自动提取为函数参数:

// Swagger: /user/{id}/posts/{postId}
export const getUserPostApi = (id: string, postId: string) => {
  return get<IGetUserPostRes>(`/user/${id}/posts/${postId}`);
};

作者信息提取

按以下优先级:

  1. API 的 x-author 字段
  2. Swagger 的 info.contact.name
  3. 配置文件中的 author
  4. 不生成(如果都没有)

🧪 开发与测试

# 安装依赖
npm install

# 开发模式
npm run dev

# 构建
npm run build

# 测试
npm run test

📋 注意事项

  1. $ref 引用:工具会递归解析所有 $ref,包括嵌套引用
  2. 循环引用:自动检测并打印警告,避免死循环
  3. 空参数处理:没有参数的 API 不会生成 data 参数
  4. 命名冲突:自动为重复的 operationId 添加数字后缀
  5. 格式化选项:启用 format: true 需要项目中已配置 eslint 和 prettier