1.2.0 • Published 3 months ago

openapi-ts-request v1.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
3 months ago

介绍

GitHub Repo stars npm (scoped) GitHub tag

English | 简体中文

根据 Swagger2/OpenAPI3/Apifox 文档生成:

  • TypeScript/JavaScript
  • 客户端请求函数(支持任意客户端)
  • 模拟请求响应服务
  • 枚举和枚举翻译
  • react-query/vue-query
  • 类型字段翻译
  • JSON Schemas

文档:使用手册

功能

  • 支持 Swagger2.0/OpenAPI/Apifox 3.0,3.1 定义
  • 生成 TypeScript/JavaScript, 请求客户端(支持任意客户端), 请求模拟服务, 枚举和枚举翻译, react-query/vue-query, 类型字段翻译, JSON Schemas
  • 支持通过 npx、CLI、Nodejs 的方式使用
  • 支持自定义请求工具函数, 支持 Fetch、Axios、UniApp-Request、Taro-Request、Node.js、XHR 客户端
  • 支持通过 tags 过滤生成结果
  • 支持 JSON/YAML 定义文件
  • 支持将中文 tag 名称翻译为英文 tag 名称

使用

# npm
npm i openapi-ts-request --save-dev

# pnpm
pnpm i openapi-ts-request -D

CosmiConfig

在项目根目录新建 openapi-ts-request.config.ts

配置文件还支持 .openapi-ts-request.ts, openapi-ts-request.config.cjs 等格式,参考 cosmiconfig

import type { GenerateServiceProps } from 'openapi-ts-request';

export default {
  // schemaPath: './openapi.json', // 本地openapi文件
  // serversPath: './src/apis', // 接口存放路径
  schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
} as GenerateServiceProps;

支持传入数组配置进行生成

import type { GenerateServiceProps } from 'openapi-ts-request';

export default [
  {
    schemaPath: 'http://app.swagger.io/v2/swagger.json',
    serversPath: './src/apis/app',
  },
  {
    schemaPath: 'http://auth.swagger.io/v2/swagger.json',
    serversPath: './src/apis/auth',
  },
] as GenerateServiceProps[];

package.jsonscript 中添加命令: "openapi": "openapi-ts",

运行:

npm run openapi

生成的接口:

src/apis/index.ts #接口入口文件
src/apis/types.ts #类型定义文件
src/apis/pet.ts #接口文件
// src/apis/pet.ts
/* eslint-disable */
// @ts-ignore
import request from 'axios';

import * as API from './types';

/** Update an existing pet PUT /pet */
export async function updatePet({
  body,
  options,
}: {
  body: API.Pet;
  options?: { [key: string]: unknown };
}) {
  return request<unknown>(`/pet`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    data: body,
    ...(options || {}),
  });
}

// ... 其他接口

JS

任意目录 xxx/xxx 新建 openapi-ts-request.config.js

const { generateService } = require('openapi-ts-request');

generateService({
  schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
  serversPath: './apis',
});

package.jsonscript 中添加命令: "openapi": "node xxx/xxx/openapi-ts-request.config.js"

运行:

npm run openapi

TS

任意目录 xxx/xxx 新建 openapi-ts-request.config.ts

const { generateService } = require('openapi-ts-request');

generateService({
  schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
  serversPath: './apis',
});

package.jsonscript 中添加命令: "openapi": "ts-node xxx/xxx/openapi-ts-request.config.ts",

运行:

npm run openapi

NPX

# npm
npx --package=openapi-ts-request -- openapi -i ./openapi.json -o ./apis
npx --package=openapi-ts-request -- openapi -i https://petstore3.swagger.io/api/v3/openapi.json -o ./apis

# pnpm
pnpm --package=openapi-ts-request@latest dlx openapi -i ./openapi.json -o ./apis
pnpm --package=openapi-ts-request@latest dlx openapi -i https://petstore3.swagger.io/api/v3/openapi.json -o ./apis

CLI

npm i openapi-ts-request -g
$ openapi --help

  Usage: openapi [options]

  Options:
    -V, --version                       output the version number
    -i, --input <string>                OpenAPI specification, can be a path, url (required)
    -o, --output <string>               output directory (required)
    --requestLibPath <string>           custom request lib path, for example: "@/request", "node-fetch" (default: "axios")
    --enableLogging <boolean>           open the log (default: false)
    --priorityRule <string>             priority rule, include/exclude/both (default: "include")
    --includeTags <(string|RegExp)[]>   generate code from include tags
    --includePaths <(string|RegExp)[]>  generate code from include paths
    --excludeTags <(string|RegExp)[]>   generate code from exclude tags
    --excludePaths <(string|RegExp)[]>  generate code from exclude paths
    --requestOptionsType <string>       custom request method options parameter type (default: "{ [key: string]: unknown }")
    --requestImportStatement <string>   custom request import statement, for example: "const request = require('@/request')"
    --apiPrefix <string>                custom the prefix of the api path, for example: "api"(variable), "'api'"(string)
    --isGenReactQuery <boolean>         generate react-query (default: false)
    --reactQueryMode <string>           react-query mode, react/vue (default: "react")
    --isGenJavaScript <boolean>         generate JavaScript (default: false)
    --isDisplayTypeLabel <boolean>      generate label matching type field (default: false)
    --isGenJsonSchemas <boolean>        generate JSON Schemas (default: false)
    --mockFolder <string>               mock file path, for example: './mocks'
    --authorization <string>            docs authorization
    --nullable <boolean>                null instead of optional (default: false)
    --isTranslateToEnglishTag <boolean> translate chinese tag name to english tag name (default: false)
    --isOnlyGenTypeScriptType <boolean> only generate typescript type (default: false)
    --isCamelCase <boolean>             camelCase naming of controller files and request client (default: true)
    --isSupportParseEnumDesc <boolean>  parse enum description to generate enum label (default: false)
    -h, --help                          display help for command

运行:

openapi --i ./spec.json --o ./apis

参数

属性必填类型默认值说明
schemaPathstring-Swagger2/OpenAPI3 地址
serversPathstring'./src/apis'运行结果文件夹路径
requestLibPathstring'axios'自定义请求方法路径,例如:'@/request'、'node-fetch'
enableLoggingbooleanfalse是否开启日志
priorityRulestring'include'模式规则,可选include/exclude/both
includeTags(string|RegExp)[]-根据指定的 tags 生成代码, priorityRule=include则必填
includePaths(string|RegExp)[]-根据指定的 paths 生成代码
excludeTags(string|RegExp)[]-根据指定的 tags 不生成代码
excludePaths(string|RegExp)[]-根据指定的 paths 不生成代码
requestOptionsTypestring'{ key: string: unknown }'自定义请求方法 options 参数类型
requestImportStatementstring-自定义请求方法表达式,例如:"const request = require('@/request')"
apiPrefixstring-api path的前缀,例如:'api'(动态变量), "'api'"(字符串)
isGenReactQuerybooleanfalse是否生成 react-query
reactQueryModestring'react'react-query 模式,可选 react/vue
isGenJavaScriptbooleanfalse是否生成 JavaScript
isDisplayTypeLabelbooleanfalse是否生成 type 对应的label
isGenJsonSchemasbooleanfalse是否生成 JSON Schemas
mockFolderstring-mock文件路径,例如:'./mocks'
authorizationstring-文档权限凭证
nullablebooleanfalse使用 null 代替可选
isTranslateToEnglishTagbooleanfalse将中文 tag 名称翻译成英文 tag 名称
isOnlyGenTypeScriptTypebooleanfalse仅生成 typescript 类型
isCamelCasebooleantrue小驼峰命名文件和请求函数
isSupportParseEnumDescbooleanfalse解析枚举描述生成枚举标签,格式参考:系统用户角色:User(普通用户)=0,Agent(经纪人)=1,Admin(管理员)=2
hookCustom Hook-自定义 hook

自定义 Hook

属性类型说明
afterOpenApiDataInited(openAPIData: OpenAPIObject) => OpenAPIObject自定义 OpenAPI 数据
customFunctionName(data: APIDataType) => string自定义请求方法函数名称
customTypeName(data: APIDataType) => string自定义类型名称
customClassName(tagName: string) => string自定义标签名
customType({schemaObject: SchemaObject | ReferenceObject,namespace: string,originGetType:(schemaObject: SchemaObject | ReferenceObject, namespace: string, schemas?: ComponentsObject'schemas') => string,schemas?: ComponentsObject'schemas',}) => string自定义类型 返回非字符串将使用默认方法获取type
customFileNames(operationObject: OperationObject,apiPath: string,apiMethod: string,) => string[]自定义生成的请求客户端文件名称,可以返回多个文件名称的数组(表示生成多个文件). 返回为空,则使用默认的方法获取

JSON Schemas

  • 默认生成 components.schemas 下面的 JSON Schemas,paths 对应的 JSON Schemas 目前需自行解析
  • 提供一个解析 schema 的函数,用于将 $ref$allOf 的引用填充到 当前schema
export declare function patchSchema<T extends object>(
  schema: ISchemaObject,
  schemas: ComponentsObject['schemas']
): T;

Mock

目前使用 mockjs 生成 mock 数据,mocks 文件启动需要借助 @umijs/server,后面会寻找其他方案以达到更好的 mock 体验

适配uniapp

适配 uniapp 推荐采用自定义 request 函数的方式,你也可以使用 @uni-helper/axios-adapter 适配器,详情见 【使用手册 2.2】

贡献

环境要求

  • node 18+
  • pnpm 9+

提交 Pull Request

  1. 熟悉 Pull Request 规范
  2. fork 此仓库
  3. 开一个新分支修改代码:git checkout -b my-branch main
  4. 确保你的代码可以通过所有测试用例(新增功能需要添加新的功能测试用例):pnpm test
  5. 创建 changeset 文件通过命令:pnpm changeset
  6. 使用 commit 提交你的修改(需遵循 commitlint 规范)
  7. 发起 Pull Request

感谢

1.2.0

3 months ago

1.0.1

5 months ago

1.0.0

5 months ago

0.8.4

8 months ago

0.11.0

7 months ago

0.11.1

7 months ago

0.13.0

7 months ago

0.13.1

7 months ago

0.13.2

6 months ago

0.13.3

6 months ago

0.13.4

6 months ago

0.9.0

7 months ago

1.1.1

5 months ago

1.1.0

5 months ago

1.1.2

5 months ago

0.12.0

7 months ago

0.12.1

7 months ago

0.10.0

7 months ago

0.8.3

8 months ago

0.8.2

8 months ago

0.8.1

8 months ago

0.4.10

10 months ago

0.4.11

9 months ago

0.8.0

8 months ago

0.5.0

9 months ago

0.7.0

8 months ago

0.6.0

9 months ago

0.4.9

10 months ago

0.4.8

10 months ago

0.4.7

11 months ago

0.4.6

11 months ago

0.4.5

11 months ago

0.4.4

11 months ago

0.4.3

11 months ago

0.4.2

11 months ago

0.4.1

11 months ago

0.4.0

11 months ago

0.3.4

11 months ago

0.3.3

11 months ago

0.3.2

11 months ago

0.3.1

11 months ago

0.3.0

11 months ago

0.2.0

11 months ago

0.1.3

12 months ago

0.1.2

12 months ago

0.1.1

12 months ago

0.1.0

12 months ago