-
Notifications
You must be signed in to change notification settings - Fork 35
/
pontTemplate.ts
283 lines (238 loc) · 7.41 KB
/
pontTemplate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import Pont, { CodeGenerator, Interface, Property } from '@td-design/pont-engine';
export class FileStructures extends Pont.FileStructures {
getDataSourcesTs() {
const dsNames = this.getMultipleOriginsDataSourceName();
const generatedCode = '(global as any)';
return `
${dsNames
.map(name => {
return `import { defs as ${name}Defs, ${name} } from './${name}';
`;
})
.join('\n')}
${generatedCode}.defs = {
${dsNames.map(name => `${name}: ${name}Defs,`).join('\n')}
};
${generatedCode}.API = {
${dsNames.join(',\n')}
};
`;
}
}
export default class MyGenerator extends CodeGenerator {
enum: Array<string | number> = [];
setEnum(enums: Array<string | number> = []) {
this.enum = enums.map(value => {
if (typeof value === 'string') {
if (!value.startsWith("'")) {
value = `'${value}`;
}
if (!value.endsWith("'")) {
value = `${value}'`;
}
}
return value;
});
}
/** 获取总的类型定义代码 */
getDeclaration() {
return `
type ObjectMap<Key extends string | number | symbol = any, Value = any> = {
[key in Key]: Value;
}
interface AjaxResponse<T> {
code: number;
data: T;
message: string;
success: boolean;
}
${this.getCommonDeclaration()}
${this.getBaseClassesInDeclaration()}
${this.getModsDeclaration()}
`;
}
/** 获取所有基类文件代码 */
getBaseClassesIndex() {
const clsCodes = this.dataSource.baseClasses.map(
base => `
class ${base.name} {
${base.properties
.map(prop => {
return this.toPropertyCodeWithInitValue(prop, base.name);
})
.filter(id => id)
.join('\n')}
}
`
);
if (this.dataSource.name) {
return `
${clsCodes.join('\n')}
export const ${this.dataSource.name} = {
${this.dataSource.baseClasses.map(bs => bs.name).join(',\n')}
}
`;
}
return clsCodes.map(cls => `export ${cls}`).join('\n');
}
toPropertyCodeWithInitValue(prop: Property, baseName = '') {
this.setEnum(prop.dataType.enum);
const { typeName, isDefsType } = prop.dataType;
let typeWithValue = `= ${this.getInitialValue(typeName, isDefsType, false)}`;
if (prop.dataType.typeName === baseName) {
typeWithValue = '= {}';
}
let propName = prop.name;
if (!propName.match(/^[a-zA-Z_$][a-zA-Z0-9_$]*$/)) {
propName = `'${propName}'`;
}
return `
/** ${prop.description || prop.name} */
${propName} ${typeWithValue}
`;
}
initClassValue(isDefsType: boolean, usingDef: boolean, typeName: string) {
const originName = this.dataSource.name;
if (!usingDef) {
return `new ${typeName}()`;
}
return `new ${this.getDefName(originName, typeName, isDefsType)}()`;
}
initEnumValue() {
const str = this.enum[0];
if (typeof str === 'string') {
return `${str}`;
}
return `${str}`;
}
getInitialValue(typeName: string, isDefsType: boolean, usingDef = true) {
if (isDefsType) {
return this.initClassValue(isDefsType, usingDef, typeName);
}
if (this.enum && this.enum.length) {
return this.initEnumValue();
}
return this.initNormalTypeValue(typeName);
}
/** 生成的api.d.ts文件中的对应每个接口的内容 */
getInterfaceContentInDeclaration(inter: Interface) {
const paramsCode = inter.getParamsCode();
const bodyParamsCode = inter.getBodyParamsCode();
const hasGetParams = !!inter.parameters.filter(param => param.in !== 'body').length;
let requestParams = bodyParamsCode ? `bodyParams: ${bodyParamsCode}, params: Params` : 'params: Params';
if (!hasGetParams) {
requestParams = bodyParamsCode ? `bodyParams: ${bodyParamsCode}` : '';
}
return `
/** 请求参数 */
export ${paramsCode}
/** 请求结果 */
export type Response = ${inter.responseType}
/** 用于取消请求 */
export const controller: AbortController;
/** 请求方法 */
export function fetch(${requestParams}): Promise<Response>;
`;
}
/** 生成的接口请求部分 */
// eslint-disable-next-line complexity
getInterfaceContent(inter: Interface) {
// type为body的参数
const bodyParamsCode = inter.getBodyParamsCode();
// 判断是否有params参数
const hasGetParams = !!inter.parameters.filter(param => param.in !== 'body').length;
let requestParams = bodyParamsCode ? 'data = {}, params = {}' : 'params = {}';
let requestStr = bodyParamsCode ? 'data, params' : 'params';
if (!hasGetParams) {
requestParams = bodyParamsCode ? 'data = {}' : 'params = {}';
requestStr = bodyParamsCode ? 'data' : 'params';
}
const requestObj = this.getRequest(bodyParamsCode, inter.method);
let defsStr = '';
if (inter.response.isDefsType) {
defsStr = "import * as defs from '../../baseClass';";
}
return `
/**
* @description ${inter.description}
*/
${defsStr}
import { initRequest } from '../../../../common';
import Config from 'react-native-config';
/** 用于取消请求 */
export const controller = new AbortController();
/** 请求方法,异常情况需要自己在业务端进行处理 */
export async function fetch(${requestParams}) {
const request = initRequest();
request.defaults.headers.common['Content-Type'] = '${requestObj.contentType}';
const {data: result} = await request<AjaxResponse>({
method: '${requestObj.method}',
baseURL: Config['${this.dataSource.name}'],
url: "${inter.path}",
${requestStr},
signal: controller.signal,
});
if (result) {
if (!result.success && result.code !== 20000) {
throw new Error(JSON.stringify(result));
} else {
return result.data;
}
} else {
throw new Error(JSON.stringify({ message: '接口未响应' }));
}
}
`;
}
getDefName(originName: string, typeName: string, isDefsType: boolean) {
let name = typeName;
if (isDefsType) {
name = originName ? `defs.${originName}.${typeName}` : `defs.${typeName}`;
}
return name;
}
initNormalTypeValue(typeName: string) {
switch (typeName) {
case 'Array':
return '[]';
case 'boolean':
return 'false';
case 'string':
return "''";
case 'number':
default:
return 'undefined';
}
}
// eslint-disable-next-line complexity
getRequest(bodyParamsCode: string, method: string) {
// 为避免method匹配不上,全部转化为大写
const upperMethod = method.toUpperCase();
const fetchMethod = bodyParamsCode ? `${upperMethod}:JSON` : upperMethod;
let methodTemp = '';
let contentType = 'application/json';
switch (fetchMethod) {
case 'GET':
default:
methodTemp = 'get';
break;
case 'PUT':
methodTemp = 'put';
break;
case 'DELETE':
methodTemp = 'delete';
break;
case 'POST':
methodTemp = 'post';
contentType = 'application/x-www-form-urlencoded';
break;
case 'POST:JSON':
methodTemp = 'post';
break;
}
return {
method: methodTemp,
contentType,
};
}
}