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

@cjsound/openapi-gen

v0.1.0

Published

通用 OpenAPI / Swagger TS 代码生成工具,可自定义请求函数模板与命名规则

Readme

@cjsound/openapi-gen

通用 OpenAPI / Swagger TS 代码生成工具,任意前端项目都能用。一行命令生成请求函数 + 类型定义。

特性

  • 三种用法:CLI / 配置文件 / 编程 API
  • 内置预设:cjsound-kit / axios,也可自定义任意请求库
  • 全套钩子:tagFilter / moduleName / naming / renderType / afterGenerate
  • 自动检测项目里的 prettier 做格式化(无 prettier 时跳过,零依赖)
  • 类型友好:defineConfig({...}) 配 IDE 自动补全
  • 单文件 __types.ts 集中所有 DTO,按模块拆请求函数

安装

npm i -D @cjsound/openapi-gen
# 或
yarn add -D @cjsound/openapi-gen

用法 1: 纯 CLI

npx openapi-gen \
  --schema=http://localhost:3000/api/docs-json \
  --tag=_app_ \
  --out=src/api \
  --request=cjsound-kit

| 参数 | 说明 | |---|---| | --schema <url> | OpenAPI schema 地址(URL 或本地 JSON 路径) | | --tag <substring> | 仅生成 tag 包含该子串的接口 | | --out <dir> | 输出目录(默认 src/apiService/modules) | | --request <preset> | cjsound-kit | axios | | --config <path> | 指定配置文件路径 | | --no-prettier | 跳过格式化 | | --no-index | 不生成 index.ts 聚合 | | -h, --help | 帮助 |

用法 2: 配置文件 + CLI

项目根创建 openapi.config.ts(CLI 自动加载):

import { defineConfig } from '@cjsound/openapi-gen';

export default defineConfig({
  schemaUrl: 'http://localhost:3000/api/docs-json',
  tagFilter: '_app_',
  outDir: 'src/api',
  request: 'cjsound-kit',
});

之后直接:

npx openapi-gen

CLI 参数会覆盖配置文件同名字段,方便临时切换:

npx openapi-gen --tag=_admin_ --out=src/admin-api

用法 3: 编程调用

import { generate } from '@cjsound/openapi-gen';

await generate({
  schemaUrl: 'http://localhost:3000/api/docs-json',
  tagFilter: '_app_',
  outDir: 'src/api',
});

适合放在自定义脚本里,搭配你自己的预处理 / 多次生成等场景。

配置完整字段

interface UserConfig {
  // ---- 必填 ----
  schemaUrl: string;

  // ---- 输出 ----
  outDir?: string;            // 默认 'src/apiService/modules'
  typesFileName?: string;     // 默认 '__types'
  generateIndex?: boolean;    // 默认 true

  // ---- 筛选 ----
  tagFilter?:                 // 默认全部生成
    | string                  // tag.includes(...)
    | ((tag: string, op: { url: string; method: HttpMethod }) => boolean);

  moduleName?: (tag: string) => string;
  // 默认: tagFilter 是 string 时取 tag.split(filter)[1]

  // ---- 命名 ----
  naming?: (ctx: { modName: string; methodName: string; operationId?: string }) => string;
  // 默认: ({modName, methodName}) => `${modName}${capitalize(methodName)}`  (驼峰)

  // ---- 请求库 ----
  request?: 'cjsound-kit' | 'axios' | RequestPreset;

  // ---- 类型渲染 ----
  renderType?: (schema: any) => string;

  // ---- 文件头 ----
  fileHeader?: string[];      // 自定义注释行

  // ---- 钩子 ----
  afterGenerate?: (ctx: { outDir: string; files: string[]; modules: ModuleMap }) => void | Promise<void>;

  // ---- prettier ----
  prettier?: boolean;         // 默认 true (检测项目里装了才用)
}

自定义 request 预设

如果你的项目用了独家 SDK,写个 RequestPreset 喂给 request

import { defineConfig, RequestPreset } from '@cjsound/openapi-gen';

const myKit: RequestPreset = {
  importStatement: "import http from '@/utils/http';",
  pickFn: (method) => `http.${method}`,
  buildCall: ({ fnName, urlExpr, hasBody, hasQuery, responseType }) => {
    const generic = responseType ? `<${responseType}>` : '';
    if (hasBody) return `${fnName}${generic}(${urlExpr}, { body: data })`;
    if (hasQuery) return `${fnName}${generic}(${urlExpr}, { query })`;
    return `${fnName}${generic}(${urlExpr})`;
  },
};

export default defineConfig({
  schemaUrl: 'http://localhost:3000/api/docs-json',
  request: myKit,
});

自定义筛选 / 命名 / 模块名

export default defineConfig({
  schemaUrl: '...',
  // 完全自定义筛选
  tagFilter: (tag, op) => tag.startsWith('App__') && !op.url.includes('/internal/'),
  // 完全自定义模块名
  moduleName: (tag) => tag.replace(/^App__/, '').toLowerCase(),
  // 自定义函数名: home_getList → useHome_GetList
  naming: ({ modName, methodName }) => `use${capitalize(modName)}_${capitalize(methodName)}`,
});

生成产物示例

输入:tagFilter: '_admin_',后端有 用户管理__admin_user 这个 tag。

输出 src/apiService/modules/

__types.ts        # 71 个 DTO interface
user.ts           # 8 个 user 接口函数
role.ts           # 8 个 role 接口函数
...
index.ts          # 聚合 export default { user, role, ... }

user.ts 内容:

import { requestGet, requestPost, requestPut, requestDelete } from 'cjsound-kit';
import type { CreateUserDto, UpdateUserDto, ResultDataUserDtoDto } from './__types';

/** 根据ID获取用户 */
export const userGetUserById = (params: { id: number }) => {
  return requestGet<ResultDataUserDtoDto>(`apiAdmin/user/${params.id}`);
};

/** 创建用户 */
export const userCreateUser = (data: CreateUserDto) => {
  return requestPost<ResultDataUserDtoDto>('apiAdmin/user', data);
};

钩子使用:afterGenerate 自定义后处理

import { execSync } from 'child_process';

export default defineConfig({
  schemaUrl: '...',
  afterGenerate({ files }) {
    // 比如对生成结果跑 ESLint --fix
    execSync(`eslint --fix ${files.join(' ')}`, { stdio: 'inherit' });
  },
});

关于 .ts 配置加载

CLI 默认尝试用 ts-node 加载 .ts 配置。如果项目没装:

npm i -D ts-node

或把配置改为 .js / .mjs / .cjs 也行:

// openapi.config.js
module.exports = {
  schemaUrl: 'http://localhost:3000/api/docs-json',
  tagFilter: '_app_',
};

License

MIT