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

@happygen/openapi-axios

v0.1.5

Published

OpenAPI ➡️ Axios

Downloads

4

Readme

openapi-axios

OpenAPI ➡️ Axios

code-review dependency-review Codacy Badge Codacy Badge npm version

将 OpenAPI 规范声明文件转换为类型声明和可执行函数(基于 Axios)。与其他同类工具相比,具有以下特点:

  • 😆 支持 openAPI v3(当前仅)
  • 😉 每个 API 都是一个函数,用于在构建时轻松进行 tree shaking
  • 😎 与最流行的 HTTP 客户端 axios 进行适配
  • 🤗 轻松与本地请求客户端集成,例如在本地项目中创建的 Axios 实例(通常我们在本地都是需要自定义一些拦截器什么的)
  • 😁 易于使用,易于学习,类型安全

安装

npm i -D @happygen/openapi-axios
yarn add --dev @happygen/openapi-axios
pnpm i -D @happygen/openapi-axios

使用

命令行

在项目根目录下创建配置文件,配置文件的搜索顺序是 openapi.config.cjsopenapi.config.js

// openapi.config.cjs
const { defineConfig } = require('@happygen/openapi-axios');

module.exports = defineConfig({
  openAPIs: [
    {
      // 将会生成 src/apis/swagger/petStore3.ts 文件
      name: 'swagger/petStore3',
      // 可以是一个 URL 链接或者本地路径,或者一个 OPENAPI3 文档对象
      document: 'https://petstore3.swagger.io/api/v3/openapi.json',
    },
  ],
});

swagger-url-position.png

# 根据配置文件生成typescript文件
npx openapi-axios

# 将会生成 src/apis/swagger/petStore3.ts 文件
// src/apis/swagger/petStore3.ts

import type { OneOf } from '@happygen/openapi-axios/helpers';
import type { AxiosPromise, AxiosRequestConfig } from 'axios';
import {
  DELETE,
  GET,
  HEAD,
  OPTIONS,
  PATCH,
  POST,
  PUT,
  resolveURL,
} from '@happygen/openapi-axioshelpers';
import axios from 'axios';

const request = axios.request;
const BASE_URL = '/api/v3';

// ...

export type Pet = {
  category?: Category;
  /**
   * @format int64
   * @example 10
   */
  id?: number;
  /**
   * @example doggie
   */
  name: string;
  photoUrls: Array<string>;
  /**
   * @description pet status in the store
   */
  status?: 'available' | 'pending' | 'sold';
  tags?: Array<Tag>;
};

// ...

export type AddPetReqData = Pet;
export type AddPetResData = Pet;
/**
 * @title Add a new pet to the store
 * @description Add a new pet to the store
 */
export async function addPet(
  data: AddPetReqData,
  config?: AxiosRequestConfig
): AxiosPromise<AddPetResData> {
  return request({
    url: resolveURL(BASE_URL, `/pet`),
    method: POST,
    data,
    ...config,
  });
}

// ...

然后你可以直接导入一个函数并使用它。 调用接口就像调用本地函数一样简单,是不是类似于 RPC(remote procedure call)。

import { addPet } from '@/apis/swagger/petStore3';

// 类型安全
const { data: pet } = await addPet({
  name: 'MyCat',
  photoUrls: ['photo1', 'photo2']
});

// 类型安全
console.log(pet);

openapi.config

| 参数名 | 类型 | 可选性 | 描述 | 默认值 | |------------|--------------------|---------|----------------------------|-----------------------------| | cwd | string | false | 当前工作路径 | process.cwd() | | dest | string | false | 目标目录 | src/apis | | dts | string | false | dts输出目录 | src/apis | | parser | ParserOptions | false | 解析配置 | undefined | | printer | PrinterOptions | false | 输出配置 | undefined | | openAPIs | OpenAPIOptions[] | true | OpenAPIOptions 列表,至少需要配置一个 | 无 |

ParserOptions 签名:

| 参数名 | 类型 | 可选性 | 描述 | 默认值 | |------------------------|------------|---------|----------------------------------------------------------------|------------------------| | cwd | string | false | 当前工作路径 | process.cwd() | | okCode | number | false | ok 的响应码 | 200 | | okMediaType | number | false | ok 的响应类型 | application/json | | nameFormatter | function | false | 自定义name格式化方法,函数签名 (props: NameFormatterProps) => string; | ({name}) => name | | requestPathTypeName | string | false | 请求路径参数类型名称 | ReqPath | | requestQueryTypeName | string | false | 请求查询参数类型名称 | ReqParams | | requestBodyTypeName | string | false | 请求体参数类型名称 | ReqData | | responseBodyTypeName | string | false | 响应体参数类型名称 | ResData |

NameFormatterProps 签名:

| 参数名 | 类型 | 可选性 | 描述 | 默认值 | |-----------------------|----------|---------|--------------------|-----------------------------| | name | string | true | 原始名称(经过内部处理,能保证唯一) | 无 | | method | string | true | 方法 | 无 | | path | string | true | 路径 | 无 | | operationId | string | false | operationId | 无 |

PrinterOptions 签名:

| 参数名 | 类型 | 可选性 | 描述 | 默认值 | |-----------------------|----------|---------|-------------------------------------|-----------------------------| | axiosImport | string | false | axios 导入内容 | 默认从官方 Axios 导入,可以使用自己实现的客户端 | | prettier | object | false | prettier 配置 | { singleQuote: true } | | requestPathArgName | string | false | 请求路径参数入参名称 | path | | requestQueryArgName | string | false | 请求查询参数入参名称 | params | | requestBodyArgName | string | false | 请求体参数入参名称 | data | | responseTypeName | string | false | 响应类型名称 | AxiosPromise |

OpenAPIOptions 签名:

| 名称 | 类型 | 可选 | 描述 | 默认值 | |------------|---------------------------|----|--------------------------------------------------|-------------| | name | string | 必须 | openapi 的名称,将会生成 ${name}.ts 文件 | undefined | | document | string,OpenAPI3Document | 必须 | openapi 文档,可以是一个 URL 链接或者本地路径,或者一个 OPENAPI3 文档对象 | undefined |