UNPKG

5.81 kBMarkdownView Raw
1# sm2tsservice
2
3## start
4
5```shell
6 cd yourProjectName
7 java -version
8 npm i sm2tsservice -D
9```
10
11## config
12
13edit json2service.json
14
15| 参数 | 值 | 说明 |
16| ---------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
17| url | url 或者文件地址 | swagger、yapi 文档 url 地址或者文件目录,注意:如果是本地文件,文件名不能以 http 开头 |
18| type | yapi、swagger | 标记类型,默认是 swagger |
19| swaggerParser | | swagger-code-gen 配置 |
20| | -o | 输出 typescript 代码目录,默认是当前 src/services |
21| | -t | 模板目录,默认是工具内置模板目录 plugins/typescript-tkit/,避免修改 |
22| | -l | 模板目录,默认是 typescript-angularjs,避免修改 |
23| validateResponse | boolean | 是否生成校验逻辑,默认 false,[详细文档](./src/validate/README.md) |
24| yapiConfig | | yapi 相关配置 |
25| | required | 当直接使用 yapi json 定义返回数据格式的时候,生成的 typescript 文件,默认情况下,所有字段都是可选的,配置成 true,则所有字段都是不可缺省的 |
26| | bodyJsonRequired | 当直接使用 yapi json 定义 json 格式 body 参数的时候,生成的 typescript 文件,默认情况下,所有字段都是可选的,配置成 true,则所有字段都是不可缺省的 |
27
28```json
29{
30 "url": "./api.json",
31 "type": "yapi",
32 "yapiConfig": {
33 "required": false,
34 "bodyJsonRequired": false
35 },
36 "swaggerParser": {
37 "-o": "tmp/services"
38 },
39 "validateResponse": false // 是否生成校验逻辑
40}
41```
42
43参考下方代码,实现 ajax 类【如果使用的 axios,且后端返回数据结构遵循 `{ code?:number;message?:string;result: any }`,可直接复制使用】
44
45```ts
46import axios, { AxiosError } from 'axios';
47import qs from 'qs';
48
49const inst = axios.create({
50 timeout: 2000,
51 withCredentials: true,
52 headers: {}
53});
54
55// @cc: 检测 axios 响应状态
56function onStatusError(error: AxiosError | Error) {
57 const err =
58 'response' in error && error.response
59 ? {
60 code: error.response.status,
61 message: error.response.statusText
62 }
63 : { code: 10001, message: error.message };
64 if (err.code === 401 || err.code === 403) {
65 // @todo 未登录未授权
66 // EventCenter.emit('common.user.status', err);
67 }
68 return err;
69}
70
71export type AjaxPromise<R> = Promise<R>;
72
73export interface ExtraFetchParams {
74 extra?: any;
75}
76
77export interface WrappedFetchParams extends ExtraFetchParams {
78 method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'PATCH' | 'HEAD';
79 url: string;
80 data?: any; // post json
81 form?: any; // post form
82 query?: any;
83 header?: any;
84 path?: any;
85}
86
87export class WrappedFetch {
88 /**
89 * @description ajax 方法
90 */
91 public ajax(
92 { method, url, data, form, query, header, extra }: WrappedFetchParams,
93 path?: string,
94 basePath?: string
95 ) {
96 let config = {
97 ...extra,
98 method: method.toLocaleLowerCase(),
99 headers: { ...header }
100 };
101 // json
102 if (data) {
103 config = {
104 ...config,
105 headers: {
106 ...config.headers,
107 'Content-Type': 'application/json'
108 },
109 data
110 };
111 }
112 // form
113 if (form) {
114 config = {
115 ...config,
116 headers: {
117 ...config.headers,
118 'Content-Type': 'application/x-www-form-urlencoded'
119 },
120 data: qs.stringify(form)
121 };
122 }
123 return inst
124 .request({ ...config, url, params: query })
125 .then(res => res.data)
126 .catch(onStatusError);
127 }
128
129 /**
130 * @description 接口传参校验
131 */
132 public check<V>(value: V, name: string) {
133 if (value === null || value === undefined) {
134 const msg = `[ERROR PARAMS]: ${name} can't be null or undefined`;
135 // 非生产环境,直接抛出错误
136 if (process.env.NODE_ENV === 'development') {
137 throw Error(msg);
138 }
139 }
140 }
141}
142
143export default new WrappedFetch();
144```
145
146配置 tsconfig.json[如未使用 ts-loader,还需要配置 webpack alias]
147
148```json
149{
150 "paths": {
151 "@ajax": ["你的实现文件地址"]
152 }
153}
154```
155
156```shell
157 ./node_modules/.bin/sm2tsservice # 使用默认配置
158 ./node_modules/.bin/sm2tsservice -c config.json # 指定配置文件
159 ./node_modules/.bin/sm2tsservice --clear # 清空上次生成产物
160```
161
162或可以写入 `package.json`,通过 `npm run api` 使用
163
164```json
165{
166 "scripts": {
167 "api": "sm2tsservice --clear"
168 }
169}
170```