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 🙏

© 2024 – Pkg Stats / Ryan Hefner

swaggered

v1.7.1

Published

Generate client request code with TypeScript typings from Swagger OpenAPI JSON Schema.

Downloads

115

Readme

Swaggered

从 Swagger JSON Schema 生成 TypeScript 客户端请求代码并带有严格的 TS 类型丰富的注释

Generate client request code with TypeScript typings and as many comments as possible from Swagger OpenAPI Schema.

Generated Example:

/** Comment about this service from schema description */
export const JobService = {
  // 🔥 Grouped by path or tag, nicely organized. Give it a try by passing the `grouped` flag
  prefix: '/api/model/v1/evaluate/job',

  /**
   * Comment about getJobDetail
   */
  async getJobDetail(params: IGetJobDetailParams) {
    return request<Data<IGetJobDetailRespData>>(`${this.prefix}/${params.jobId}`, {
      method: 'GET',
    });
  },

  /**
   * Comment about createJob
   */
  async createJob(data: ICreateJobReqData) {
    return request<Data<ICreateJobRespData>>(this.prefix, {
      method: 'POST',
      data: ICreateJobReqData
    });
  },

  /**
   * Comment about stopJob
   */
  async stopJob(params: IStopJobParams) {
    return request<Data<IStopJobRespData>>(`${this.prefix}/${params.jobId}`, {
      method: 'POST',
    });
  },
};

// 🔥 Generate **Generic Response Type** from parsing your response structure intelligently!
type Data<T> = {
  code: number;
  data: T;
  message: string;
}

// ... other types omitted

Features

  • [x] Strict TS Types: Generate client code with strict TS types and keep the original comments in tsdoc
  • [x] Filterable: You can generate only what you need using filter by api path and HTTP method
  • [x] Flexible Usage: Can be used through CLI or programmatically
  • [x] Flexible Format:
    • [x] 🔥 You can generate standalone request functions or
    • [x] 🔥 Grouped by path or tag. Nicely organized. Give it a try!
    • [x] 🔥 Generate Generic Response Type from parsing your response structure intelligently!
  • [x] Pretty Print: 🔥 Highlight output with shikijs
  • [x] Battlefield tested: Support all Swagger OpenAPI versions and Node.js from v16 to v22
  • [x] Unit tested: Coverage (2024-08-15) all files line: 95.68, branch: 85.16, funcs: 95.08

Get Started

1. Use CLI RECOMMENDED

Generate request code with api contains foo only:

Output to stdout

npx swaggered --input ./assets/openapi.json --api foo

Copy to clipboard

# macOS
npx swaggered --input ./assets/openapi.json --api foo | pbcopy

# Windows
npx swaggered --input ./assets/openapi.json --api foo | clip

Save to file

npx swaggered --input ./assets/openapi.json --api foo > ./src/service/foo.ts
┌──────────────┬───────────┬───────┬───────────────────────────────────────┬──────────┬─────────┐
│ (index)      │ type      │ short │ description                           │ required │ default │
├──────────────┼───────────┼───────┼───────────────────────────────────────┼──────────┼─────────┤
│ help         │ 'boolean' │ 'h'   │ 'Show this help message'              │ '×'      │ false   │
│ input        │ 'string'  │ 'i'   │ 'Input file path of swagger json'     │ '√'      │         │
│ api          │ 'string'  │ 'a'   │ 'Generate typings match the API path' │ '×'      │ '*'     │
│ method       │ 'string'  │ 'm'   │ 'Generate code match the HTTP method' │ '×'      │ '*'     │
│ debug        │ 'boolean' │ 'd'   │ 'Print debug info'                    │ '×'      │ false   │
│ typesOnly    │ 'boolean' │ 't'   │ 'Generate only types'                 │ '×'      │ false   │
│ functionOnly │ 'boolean' │ 'f'   │ 'Generate only functions'             │ '×'      │ false   │
│ grouped      │ 'boolean' │ 'g'   │ 'Print functions by group'            │ '×'      │ false   │
└──────────────┴───────────┴───────┴───────────────────────────────────────┴──────────┴─────────┘
  • input is required only.
  • grouped is my favorite flag, it will generate request functions by group. Give it a try!

2. Use programmatically. generateTSFromSchema

import { prettyPrint, generateTSFromSchema } from 'swaggered';

const result = await generateTSFromSchema({
  openapi: '3.0.1',
  info: {
    title: 'OpenAPI definition',
    version: 'v0',
  },
  servers: [
    {
      url: 'http://127.0.0.1:8000',
      description: 'Generated server url',
    },
  ],
  paths: {
    '/api/bar/v1/baz/foo/list': {
      get: {
        tags: ['foo的相关接口'],
        summary: '分页查询foo作业',
        description: '分页查询foo作业',
        operationId: 'listFoo',
        parameters: [
          {
            name: 'req',
            in: 'query',
            required: true,
            schema: {
              $ref: '#/components/schemas/PageRequest',
            },
          },
        ],
        responses: {
          200: {
            description: '服务Okay,但请求是否成功请看返回体里面的code',
            content: {
              '*/*': {
                schema: {
                  $ref: '#/components/schemas/ResponsePageVOEvaluateFooResp',
                },
              },
            },
          },
        },
      },
    },
  },
  components: {
    schemas: {
      PageRequest: {
        required: ['current', 'pageSize'],
        type: 'object',
        properties: {
          current: {
            minimum: 1,
            type: 'integer',
            description: 'current',
            format: 'int32',
          },
          pageSize: {
            maximum: 1000,
            type: 'integer',
            description: 'pageSize',
            format: 'int32',
          },
        },
      },
      EvaluateFooResp: {
        type: 'object',
        properties: {
          id: {
            type: 'integer',
            format: 'int64',
          },
          name: {
            type: 'string',
          },
          description: {
            type: 'string',
          },
          status: {
            type: 'string',
            enum: ['XX', 'YY', 'COMPLETED', 'FAILED'],
          },
          bars: {
            type: 'array',
            items: {
              type: 'string',
            },
          },
        },
      },
      PageVOEvaluateFooResp: {
        type: 'object',
        properties: {
          total: {
            type: 'integer',
            format: 'int64',
          },
          pageSize: {
            type: 'integer',
            format: 'int32',
          },
          current: {
            type: 'integer',
            format: 'int32',
          },
          list: {
            type: 'array',
            items: {
              $ref: '#/components/schemas/EvaluateFooResp',
            },
          },
        },
      },
      ResponsePageVOEvaluateFooResp: {
        type: 'object',
        properties: {
          code: {
            type: 'integer',
            format: 'int32',
          },
          data: {
            $ref: '#/components/schemas/PageVOEvaluateFooResp',
          },
          errorMsg: {
            type: 'string',
          },
          success: {
            type: 'boolean',
          },
        },
      },
    },
  },
});

await prettyPrint(result);

3. Use programmatically. Generate from file and prettyPrint automatically

import { swaggerToTS } from 'swaggered';

await swaggerToTS({
  input: swaggerJsonFilepath,
  api: 'baz',
  // method: '*',
});

4. Use Programmatically. Generate from file and prettyPrint result or do whatever you want

import { generateTSFromFile, prettyPrint } from 'swaggered';

const result = await generateTSFromFile(filepath, {
  typesOnly: false,
  filter: {
    api,
    method,
  },
});

prettyPrint(result, { debug, typesOnly });
interface IResult {
  list: IGeneratedItem[];
  total: number;
}

interface IGeneratedItem
 /** API path */
 path: string;

 /** HTTP method */
 method: string;

 /** HTTP request parameters type */
 requestParametersType: string;

 /** HTTP request body type */
 requestBodyType: string;

 /** HTTP response type */
 responseType: string;
export async function list(params: PagedQueryBarsParams) {
  return request<Data<PagedQueryBarsRespData>>('/api/foo/v1/bars', {
    method: 'GET',
    params,
  });
}

type Data<T> = {
  code: number;
  data: T;
  message: string;
};

interface PagedQueryBarsParams {
  /**
   * 页码,必填,必须大于0
   */
  page_number: number;
  /**
   * 每页数量,必填,必须大于等于1且小于21
   */
  page_size: number;
  /**
   * bar name,模糊匹配,可空
   */
  bar_name?: string | null;
  /**
   * bar状态,0:未激活,1:激活,2:已过期,3:已删除,可为空,也可以包含一个或多个
   */
  status_list?: ("0" | "1" | "2" | "3")[] | null;
  /**
   * bar开始时间,可为空
   */
  start_time?: string | null;
  /**
   * bar结束时间,可为空
   */
  end_time?: string | null;
}

interface BaseResponsePagedQueryBarsResponse {
  code: number;
  message?: string | null;
  data?: PagedQueryBarsRespData | null;
}
interface PagedQueryBarsRespData {
  /**
   * bars总数
   */
  total: number;
  bars: GetBarRespData[];
}
interface GetBarRespData {
  /**
   * bar id,必定存在
   */
  bar_id: number;
  /**
   * bar name,必定存在
   */
  bar_name: string;
  /**
   * bar的创建时间,必定存在
   */
  created_time: string;
  /**
   * bar的上次更新时间,必定存在
   */
  updated_time: string;
}