Gathering detailed insights and metrics for ts-gear
Gathering detailed insights and metrics for ts-gear
npm install ts-gear
Typescript
Module System
Node Version
NPM Version
49.7
Supply Chain
92
Quality
73.3
Maintenance
50
Vulnerability
97.3
License
TypeScript (98.84%)
JavaScript (1.14%)
Shell (0.02%)
Total Downloads
16,805
Last Day
7
Last Week
64
Last Month
228
Last Year
2,403
26 Stars
278 Commits
7 Forks
3 Watching
4 Branches
3 Contributors
Minified
Minified + Gzipped
Latest Version
4.11.8
Package Id
ts-gear@4.11.8
Unpacked Size
324.33 kB
Size
79.90 kB
File Count
188
NPM Version
9.8.1
Node Version
18.18.0
Publised On
20 May 2024
Cumulative downloads
Total Downloads
Last day
-50%
7
Compared to previous day
Last week
137%
64
Compared to previous week
Last month
51%
228
Compared to previous month
Last year
-28.1%
2,403
Compared to previous year
21
1
39
自动从swagger生成ts类型与请求接口的函数
方便的感知后端接口定义的变化。
inspired by pont
ts-gear
命名:ts是typescript与swagger的组合,gear寓意通过这个工具像齿轮一样,将前后端紧密的结合在一起,构成一架严密运转的机器。
后来想想,其实应该是与openapi结合而不仅限与swagger,不过名字起了挺久那就这样吧不改了。
1yarn add ts-gear -D 2// or 3npm install ts-gear -D
在项目src
目录下生成配置文件tsg.config.ts
。
1tsg -i
💡 因为该配置文件与请求函数有关,会在生成的代码调用,因此放到src
文件夹中。
1npx tsg // default use `src/tsg.config.ts` 2// or assign another config file 3npx tsg -c other_dir/tsg.config.ts 4// or if only need update one project, use -p for the project name 5npx tsg -p pet
src/service
文件夹,结构如下1▾ src/ 2 tsg.config.ts 3 ▾ service/ 4 ▾ pet/ 5 definition.ts 6 request.ts 7 index.ts
例如:在src/store/pet.ts
文件中
1import { getPetPetId } from '../../service/pet' 2 3getPetPetId({ 4 path: { 5 petId: 1 6 } 7}).then(pet => { 8 console.log(pet) 9 // pet will be the instance of Pet, it has Pet properties. 10})
默认请求函数的参数与返回值类型不在导出,推荐使用类型工具Parameters
与ReturnType
来从请求函数类型本身获取。
如果需要导出参数与返回值类型,可配置项目中的
1shouldExportRequestOptionType: true 2shouldExportResponseType: true
默认不生成mock数据,需要的话可配置shouldGenerateMock: true
,生成独立的mockRequest文件。
例如:
1generateRequestFunctionName: ({ 2 httpMethod: 'get' | 'put' | 'post' | 'delete' | 'options' | 'head' | 'patch' 3 pathname: string 4 schema: Path // openapi类型定义中的Path,内容太多不详细说了 5}): string => { 6 return `${httpMethod}${upperFirst(pathname.repalce('/api/commonPath', ''))}` 7}
shouldGenerateMock,是否生成mock数据,默认为false,不生成。
generateRequestFunction,生成请求函数体,用这个的话,函数内容ts-gear就不再管了,完全由这个自定义函数生成,慎重使用🙏。
读取配置文件。
读取命令行参数过滤需要解析的项目。
获取各个项目的openapi数据。
如果设置了翻译,调用翻印接口。
统一格式化所有特殊字符。
解析范型名称。
将所有请求与定义名称组装到内部的全局变量中。
配置当前输出换行符。
准备好输出文件夹。
写入枚举与基础类型定义。
写入请求函数。
生成一个导出所有内容的索引文件index.ts
。
大多数其他类型的openapi生成工具对原始定义的要求较高,容错率低,而且没有做生成范型的处理。而这几项目都是本工具的重点解决亮点。
支持 OpenAPI Specification v2 v3.
tsg.config.ts
example
1import type { Project } from 'ts-gear' 2 3const projects: Project[] = [ 4 { ... } 5] 6 7export default projects
tsg.config.ts
文件所在的路径。例如该文件位置为src/tsg.config.ts
,则配置中的路径都是相对src
路径而定Option name | type | required | default | description |
---|---|---|---|---|
name | string | true | 项目名称,需符合合法变量名称 | |
dest | string | true | 输出文件夹,默认在以src 中,比如配置为service ,则实际目录为src/service | |
source | string | true | openapi文档的json定义url 可以是远程(例如: http://1.1.1.1/v2/api-docs )或本地(例如src/service/api.json ),如果远程访问有登录或其他网络问题,推荐将定义文档下载到本地 | |
fetchApiDocOption | RequestInit | (() => RequestInit | Promise<RequestInit>) | false | 配合上个配置项source ,当远程访问source 有登录或其他校验需求时,配置该项填写校验信息,该项是原生fetch 的第二个配置参数。 | |
apiFilter | RegExp | (({pathname: string, httpMethod: HttpMethod}) => boolean) | false | 生成请求函数的过滤器,一个大的api定义文档中可能大多数都用不到,使用正则或函数可仅生成自己项目需要的api函数,减轻编译负担 | |
importRequesterStatement | string | true | 例如:import axios from "axios" 或import { request } from '../your/request' ,默认导入或命名导入都可以,如果是命名导入有多个则会使用第一个作为请求函数 | |
preferClass | boolean | false | false | 会使用class而不是interface生成接口中定义的数据类型(请求参数与返回值类型不会生成) |
withHost | boolean | false | false | 为true时,每个请求函数请求的api url不再是/api/url 这种路径格式,而是http://1.1.1.1/api/url 这种完整的格式,当需要生成跨域请求时可以配置为true |
withBasePath | boolean | false | false | 为true时,每个请求url的路径前面都会加上openapi定义中的basePath 项,按需配置 |
keepGeneric | boolean | true | true | 尝试生成范型类型,虽然做了各种努力但肯定还有一些情况不能生成范型,如果运行失败可将该项设置为false |
translationEngine | 'baidu' | 'google' | false | 如果文档中确实有一些类型的东西用中文定义的,可配置翻译引擎尝试翻译 | |
shouldGenerateMock | boolean | true | 默认true,生成mock数据,如果您的项目不需要mock数据,或有自己的mock策略,可配置为false,减少生成的代码量 | |
shouldExportRequestOptionType | boolean | false | 默认false,不导出 | |
shouldExportResponseType | boolean | false | 默认false,不导出 | |
prettierConfig | Options | false | 生成文件的prettier 配置,参考prettier 官网 | |
generateRequestFunctionName | (arg: GenerateRequestFunctionNameParameter) => string | false | 生成请求函数名称的函数 | |
generateRequestFunction | (arg: GenerateRequestFunctionNameParameter) => string | false | 生成请求函数体的函数 | |
transformJS | boolean | false | false | 是否生成js 而不是ts 文件 |
useCache | boolean | false | false | 是否生成缓存,为true时会在之后优先使用缓存而不是请求实际的openapi文档,缓存位置为node_modules/.cache ,参照babel等工具的cache也放在这里。 |
EOL | string | false | '\n' | 是否生成缓存,为true时会在之后优先使用缓存而不是请求实际的openapi文档,缓存位置为node_modules/.cache ,参照babel等工具的cache也放在这里。 |
nullableFalseAsRequired | boolean | false | false | 是否使用nullable来作为生成? 的规则 |
simplifyRequestOption | boolean | false | false | 是否使用简化模式的请求参数,去掉query 或 body 的层级 |
stripBodyPropWhenOnlyOneBodyProp | boolean | false | false | 当请求的body内只有一个参数时,且该参数是一个schema,则去掉这层参数 |
requestOptionUnionType | string | false | undefined | 为请求参数的类型添加一个联合类型,具体参阅源码中的src/type , 使用该选项将使simplifyRequestOption 失效 |
shouldForceSkipRequestHeaderOption | boolean | false | false | 是否强制将生成请求参数中的header部分作为optional |
hooks | object | false | undefined | 详见 Hooks |
ts-gear
内置的axiosRequester
接受一个axios
的实例作为参数,如果没有则使用默认的axios
。
对于axios
的各种配置可自己首先创建一个axios
实例,然后传入axiosRequester
使用。
definition.ts
由definitions
部分生成,包含所有基础类型定义。
request.ts
由paths
生成,请求函数的命名规则:http request + api path
,例如:
1 "paths": { 2 "/pet": { 3 "post": { // 生成 `postPet` 4 ... 5 }, 6 }, 7 "/pet/findByTags": { 8 "get": { // 生成 'getPetFindByTags' 9 ... 10 }, 11 }, 12 "/pet/{petId}": { 13 "get": { // 生成 'getPetPetId' function 14 ... 15 }, 16 },
index.ts
是definition.ts
与request.ts
的导出出口文件。每个请求函数的入参与返回数据类型,都会生成确定的ts类型。
如果生成的请求函数不能满足需求,也可以只使用definition.ts
中的数据类型定义。
为代码生成的生命周期中提供一些中间可以插入的步骤。
beforeWriteTs: (o: { project: Project } & PrepareToWrite) => Promise
afterWriteTs: (o: { project: Project } & PrepareToWrite) => Promise
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
Found 1/27 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
license file not detected
Details
Reason
security policy file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
23 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More