Gathering detailed insights and metrics for openapi-ts-request
Gathering detailed insights and metrics for openapi-ts-request
Gathering detailed insights and metrics for openapi-ts-request
Gathering detailed insights and metrics for openapi-ts-request
Swagger2/OpenAPI3/Apifox to TS/JS, request client, mock service, enum, react-query, type field label, JSON Schemas; 根据 Swagger2/OpenAPI3/Apifox 生成 TypeScript/JavaScript, 客户端请求函数(支持任意客户端), 模拟请求响应服务, 枚举和枚举翻译, react-query, 类型的字段翻译, JSON Schemas定义, 欢迎提功能请求
npm install openapi-ts-request
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (78.81%)
JavaScript (12.1%)
Nunjucks (9.1%)
Total Downloads
7,058
Last Day
88
Last Week
193
Last Month
1,056
Last Year
7,058
MIT License
328 Stars
418 Commits
39 Forks
9 Branches
9 Contributors
Updated on May 09, 2025
Latest Version
1.4.0
Package Id
openapi-ts-request@1.4.0
Unpacked Size
182.30 kB
Size
44.27 kB
File Count
49
NPM Version
10.8.2
Node Version
20.19.1
Published on
May 08, 2025
Cumulative downloads
Total Downloads
Last Day
633.3%
88
Compared to previous day
Last Week
-10.6%
193
Compared to previous week
Last Month
39.1%
1,056
Compared to previous month
Last Year
0%
7,058
Compared to previous year
22
22
English | 简体中文
根据 Swagger2/OpenAPI3/Apifox 文档生成:
文档:使用手册
apifox
的token
和projectId
直接生成1# npm 2npm i openapi-ts-request --save-dev 3 4# pnpm 5pnpm i openapi-ts-request -D
在项目根目录新建 openapi-ts-request.config.ts
配置文件还支持 .openapi-ts-request.ts, openapi-ts-request.config.cjs 等格式,参考 cosmiconfig
1import type { GenerateServiceProps } from 'openapi-ts-request'; 2 3export default { 4 // schemaPath: './openapi.json', // 本地openapi文件 5 // serversPath: './src/apis', // 接口存放路径 6 schemaPath: 'http://petstore.swagger.io/v2/swagger.json', 7} as GenerateServiceProps;
支持传入数组配置进行生成
1import type { GenerateServiceProps } from 'openapi-ts-request'; 2 3export default [ 4 { 5 schemaPath: 'http://app.swagger.io/v2/swagger.json', 6 serversPath: './src/apis/app', 7 }, 8 { 9 schemaPath: 'http://auth.swagger.io/v2/swagger.json', 10 serversPath: './src/apis/auth', 11 }, 12] as GenerateServiceProps[];
在 package.json
的 script
中添加命令: "openapi": "openapi-ts",
运行:
1npm run openapi
生成的接口:
1src/apis/index.ts #接口入口文件 2src/apis/types.ts #类型定义文件 3src/apis/pet.ts #接口文件
1// src/apis/pet.ts 2/* eslint-disable */ 3// @ts-ignore 4import request from 'axios'; 5 6import * as API from './types'; 7 8/** Update an existing pet PUT /pet */ 9export async function updatePet({ 10 body, 11 options, 12}: { 13 body: API.Pet; 14 options?: { [key: string]: unknown }; 15}) { 16 return request<unknown>(`/pet`, { 17 method: 'PUT', 18 headers: { 19 'Content-Type': 'application/json', 20 }, 21 data: body, 22 ...(options || {}), 23 }); 24} 25 26// ... 其他接口
任意目录 xxx/xxx
新建 openapi-ts-request.config.js
1const { generateService } = require('openapi-ts-request');
2
3generateService({
4 schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
5 serversPath: './apis',
6});
在 package.json
的 script
中添加命令: "openapi": "node xxx/xxx/openapi-ts-request.config.js"
运行:
1npm run openapi
任意目录 xxx/xxx
新建 openapi-ts-request.config.ts
1const { generateService } = require('openapi-ts-request');
2
3generateService({
4 schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
5 serversPath: './apis',
6});
在 package.json
的 script
中添加命令: "openapi": "ts-node xxx/xxx/openapi-ts-request.config.ts",
运行:
1npm run openapi
1# npm 2npx --package=openapi-ts-request -- openapi -i ./openapi.json -o ./apis 3npx --package=openapi-ts-request -- openapi -i https://petstore3.swagger.io/api/v3/openapi.json -o ./apis 4 5# pnpm 6pnpm --package=openapi-ts-request@latest dlx openapi -i ./openapi.json -o ./apis 7pnpm --package=openapi-ts-request@latest dlx openapi -i https://petstore3.swagger.io/api/v3/openapi.json -o ./apis
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
-o, --output <string> output directory
-cfn, --configFileName <string> config file name
-cfp, --configFilePath <string> config file path
-u, --uniqueKey <string> unique key
--requestLibPath <string> custom request lib path, for example: "@/request", "node-fetch" (default: "axios")
-f, --full <boolean> full replacement (default: true)
--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
运行:
1openapi --i ./spec.json --o ./apis
属性 | 必填 | 类型 | 默认值 | 说明 |
---|---|---|---|---|
schemaPath | 是 | string | - | Swagger2/OpenAPI3 地址 |
serversPath | 否 | string | './src/apis' | 运行结果文件夹路径 |
requestLibPath | 否 | string | 'axios' | 自定义请求方法路径,例如:'@/request'、'node-fetch' |
full | 否 | boolean | true | 是否全量替换 |
enableLogging | 否 | boolean | false | 是否开启日志 |
priorityRule | 否 | string | 'include' | 模式规则,可选include/exclude/both |
includeTags | 否 | (string|RegExp)[] | - | 根据指定的 tags 生成代码, priorityRule=include则必填 |
includePaths | 否 | (string|RegExp)[] | - | 根据指定的 paths 生成代码 |
excludeTags | 否 | (string|RegExp)[] | - | 根据指定的 tags 不生成代码 |
excludePaths | 否 | (string|RegExp)[] | - | 根据指定的 paths 不生成代码 |
requestOptionsType | 否 | string | '{ [key: string]: unknown }' | 自定义请求方法 options 参数类型 |
requestImportStatement | 否 | string | - | 自定义请求方法表达式,例如:"const request = require('@/request')" |
apiPrefix | 否 | string | - | api path的前缀,例如:'api'(动态变量), "'api'"(字符串) |
isGenReactQuery | 否 | boolean | false | 是否生成 react-query |
reactQueryMode | 否 | string | 'react' | react-query 模式,可选 react/vue |
isGenJavaScript | 否 | boolean | false | 是否生成 JavaScript |
isDisplayTypeLabel | 否 | boolean | false | 是否生成 type 对应的label |
isGenJsonSchemas | 否 | boolean | false | 是否生成 JSON Schemas |
mockFolder | 否 | string | - | mock文件路径,例如:'./mocks' |
authorization | 否 | string | - | 文档权限凭证 |
apifoxConfig | 否 | Apifox Config | - | apifox 配置 |
nullable | 否 | boolean | false | 使用 null 代替可选 |
isTranslateToEnglishTag | 否 | boolean | false | 将中文 tag 名称翻译成英文 tag 名称 |
isOnlyGenTypeScriptType | 否 | boolean | false | 仅生成 typescript 类型 |
isCamelCase | 否 | boolean | true | 小驼峰命名文件和请求函数 |
isSupportParseEnumDesc | 否 | boolean | false | 解析枚举描述生成枚举标签,格式参考:系统用户角色:User(普通用户)=0,Agent(经纪人)=1,Admin(管理员)=2 |
hook | 否 | Custom 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[] | 自定义生成的请求客户端文件名称,可以返回多个文件名称的数组(表示生成多个文件). 返回为空,则使用默认的方法获取 |
customTemplates | { [TypescriptFileType.serviceController]?: <T, U>(item: T, context: U) => string; } | 自定义模板,详情请看源码 |
属性 | 类型 | 说明 | 必填 |
---|---|---|---|
projectId | string | 项目id | true |
apifoxToken | string | 获取 | true |
local | string | 语言(默认: zh-CN) | false |
apifoxVersion | string | 默认: 2024-03-28, 获取当前版本 | false |
includeTags | * 或 string[] | 默认: * | false |
excludeTags | string[] | 默认: [] | false |
oasVersion | string | 指定用于导出的 OpenAPI 规范的版本,可以有值如 "2.0"、"3.0"、"3.1" | '3.0' |
exportFormat | string | 指定导出的 OpenAPI 文件的格式,可以有值如 'JSON' 或 'YAML' | 'JSON' |
includeApifoxExtensionProperties | boolean | 指定是否包含 Apifox 的 OpenAPI 规范扩展字段 x-apifox | false |
addFoldersToTags | boolean | 指定是否在标签字段中包含接口的目录名称 | false |
$ref
,$allOf
的引用填充到 当前schema
1export declare function patchSchema<T extends object>( 2 schema: ISchemaObject, 3 schemas: ComponentsObject['schemas'] 4): T;
目前使用 mockjs 生成 mock 数据,mocks 文件启动需要借助 @umijs/server,后面会寻找其他方案以达到更好的 mock 体验
适配 uniapp 推荐采用自定义 request 函数的方式,你也可以使用 @uni-helper/axios-adapter
适配器,详情见 【使用手册 2.2】
openapi-ts
命令, 直接使用openapi
1import type { APIDataType } from 'openapi-ts-request/dist/generator/type'; 2import { 3 genDefaultFunctionName, 4 resolveFunctionName, 5 stripDot, 6} from 'openapi-ts-request/dist/generator/util'; 7 8export default { 9 hook: { 10 customFunctionName(data: APIDataType, prefix: string) { 11 if (data.operationId) 12 return resolveFunctionName(stripDot(data.operationId), data.method); 13 return data.method + genDefaultFunctionName(data.path, prefix); 14 }, 15 }, 16};
git checkout -b my-branch main
pnpm test
pnpm changeset
No vulnerabilities found.
No security vulnerabilities found.