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

@micl/swagger

v0.1.4

Published

micl swagger

Downloads

41

Readme

@micl/swagger

npm version npm downloads license

一个基于装饰器的 Swagger 文档生成工具,自动记录请求和响应的 Schema。

✨ 特性

  1. 基于装饰器的 API 文档生成
  2. 自动推断请求和响应的类型结构
  3. 支持类型合并(多次调用合并 Schema)
  4. 支持自定义参数名映射
  5. 完整的 TypeScript 类型支持

📦 安装

npm install @micl/swagger
# or
pnpm add @micl/swagger
# or
yarn add @micl/swagger

🎯 快速使用

定义服务和方法

import { SwaggerService, SwaggerMethod, swagger } from '@micl/swagger';
import '@micl/helper';

@SwaggerService()
class UserService {
  @SwaggerMethod({ name: 'getUser', summary: '获取用户信息' })
  async getUser(userId: string) {
    return {
      id: userId,
      name: 'John Doe',
      email: '[email protected]',
    };
  }

  @SwaggerMethod({
    name: 'createUser',
    summary: '创建用户',
    req: { dict: ['body'] },
  })
  async createUser(body: { name: string; email: string }) {
    return { id: '123', ...body };
  }
}

// 初始化配置
swagger.init({
  storePath: './swagger.json',
  logger: console,
});

// 使用服务
const service = new UserService();
await service.getUser('123');
await service.createUser({ name: 'Jane', email: '[email protected]' });

// 导出文档
swagger.toFile();

生成的 swagger.json

{
  "UserService.getUser": {
    "summary": "获取用户信息",
    "request": {
      "0": "string"
    },
    "response": {
      "id": "string",
      "name": "string",
      "email": "string"
    }
  },
  "UserService.createUser": {
    "summary": "创建用户",
    "request": {
      "body": {
        "name": "string",
        "email": "string"
      }
    },
    "response": {
      "id": "string",
      "name": "string",
      "email": "string"
    }
  }
}

📚 API 参考

swagger 对象

init(options)

初始化配置。

参数:

| 参数 | 类型 | 描述 | |------|------|------| | storePath | string | 文档存储路径,默认 ./swagger.json | | logger | any | 日志记录器,默认 console | | callFunctionLog | boolean | 是否打印调用日志,默认 false | | schemaLog | boolean | 是否打印 Schema 日志,默认 true |

swagger.init({
  storePath: './docs/swagger.json',
  logger: console,
  callFunctionLog: true,
  schemaLog: true,
});

toFile()

将收集的 Schema 写入文件。

swagger.toFile();

SwaggerService 装饰器

类装饰器,用于包装类中的所有方法,自动记录请求和响应的 Schema。可以传入配置选项来设置服务名称。

// 无参数,使用类名作为服务名
@SwaggerService()
class UserService {
  @SwaggerMethod('获取用户')
  async getUser(id: string) {
    return { id, name: 'John' };
  }
}

// 传入服务名称
@SwaggerService('MyService')
class UserService {}

// 传入配置选项
@SwaggerService({ name: 'MyService' })
class UserService {}

### SwaggerMethod 装饰器

方法装饰器,用于记录方法调用信息。

**参数:**

| 参数 | 类型 | 描述 |
|------|------|------|
| `name` | string | 方法名称(可选,默认使用方法名) |
| `summary` | string | 方法摘要 |
| `req.dict` | string[] | 参数名映射数组 |
| `req.watch` | string | 监听的参数路径 |
| `res.watch` | string | 监听的响应路径 |

```typescript
@SwaggerMethod({
  name: 'getUser',
  summary: '获取用户信息',
  req: {
    dict: ['userId', 'options'],
    watch: 'userId',
  },
  res: {
    watch: 'data',
  },
})
async getUser(userId: string, options: any) {
  return { data: { id: userId } };
}

SwaggerCore

核心类,提供底层的 Schema 解析方法。

SwaggerCore.summary(name, summary)

设置方法摘要。

SwaggerCore.summary('UserService.getUser', '获取用户信息');

SwaggerCore.parseRequest(name, args, options?)

解析请求参数。

SwaggerCore.parseRequest('UserService.getUser', ['123'], {
  dict: ['userId'],
});

SwaggerCore.parseResponse(name, response, options?)

解析响应数据。

SwaggerCore.parseResponse('UserService.getUser', { id: '123', name: 'John' });

工具函数

getTypeTree(obj)

获取对象的类型树。

getTypeTree({ name: 'test', age: 18 });
// { name: 'string', age: 'number' }

getTypeTree([1, 2, 3]);
// { type: 'array', itemType: 'number' }

mergeSchema(a, b)

合并两个 Schema。

mergeSchema({ name: 'string' }, { age: 'number' });
// { name: 'string', age: 'number' }

mergeSchema('string', 'number');
// ['string', 'number']

📝 完整示例

import { SwaggerService, SwaggerMethod, swagger } from '@micl/swagger';
import '@micl/helper';

// 初始化
swagger.init({
  storePath: './swagger.json',
  schemaLog: true,
});

@SwaggerService()
class OrderService {
  @SwaggerMethod({ summary: '获取订单列表' })
  async getOrders(params: { page: number; size: number }) {
    return {
      list: [{ id: '1', amount: 100 }],
      total: 1,
    };
  }

  @SwaggerMethod({
    summary: '创建订单',
    req: { dict: ['order'] },
  })
  async createOrder(order: { productId: string; quantity: number }) {
    return { orderId: '123', status: 'created' };
  }
}

async function main() {
  const service = new OrderService();

  await service.getOrders({ page: 1, size: 10 });
  await service.createOrder({ productId: 'p1', quantity: 2 });

  swagger.toFile();
  console.log('Swagger 文档已生成');
}

main().catch(console.error);

🤝 贡献

欢迎提交 Issue 和 Pull Request 来完善这个模块。

📄 许可证

本项目采用 ISC 许可证 - 查看 LICENSE 文件了解详情。

Copyright (c) alexgogoing [email protected]

📞 支持

如有问题或建议,请提交 Issue 或联系维护者。


@micl/swagger - 基于装饰器的 Swagger 文档生成工具 🚀