yapi-apifox-to-typescript 4.2.3 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/ApifoxToYApiData.js +312 -588
- package/lib/cjs/Generator.js +513 -1171
- package/lib/cjs/SwaggerToYApiServer.js +125 -336
- package/lib/cjs/_virtual/_rolldown/runtime.js +23 -0
- package/lib/cjs/cli.js +171 -280
- package/lib/cjs/helpers.js +125 -209
- package/lib/cjs/index.js +15 -19
- package/lib/cjs/mini-ut.js +220 -0
- package/lib/cjs/swaggerJsonToYApiData.js +268 -482
- package/lib/cjs/types.js +93 -93
- package/lib/cjs/utils.js +364 -769
- package/lib/esm/ApifoxToYApiData.d.ts +49 -0
- package/lib/esm/ApifoxToYApiData.js +310 -572
- package/lib/esm/Generator.d.ts +53 -0
- package/lib/esm/Generator.js +509 -1146
- package/lib/esm/SwaggerToYApiServer.d.ts +23 -0
- package/lib/esm/SwaggerToYApiServer.js +119 -317
- package/lib/esm/_virtual/_rolldown/runtime.js +7 -0
- package/lib/esm/cli.d.ts +4 -0
- package/lib/esm/cli.js +162 -251
- package/lib/esm/helpers.d.ts +49 -0
- package/lib/esm/helpers.js +125 -198
- package/lib/esm/index.d.ts +2 -897
- package/lib/esm/index.js +3 -2
- package/lib/esm/mini-ut.d.ts +105 -0
- package/lib/esm/mini-ut.js +198 -0
- package/lib/esm/swaggerJsonToYApiData.d.ts +6 -0
- package/lib/esm/swaggerJsonToYApiData.js +265 -469
- package/lib/esm/types.d.ts +695 -0
- package/lib/esm/types.js +87 -73
- package/lib/esm/utils.d.ts +95 -0
- package/lib/esm/utils.js +350 -720
- package/package.json +49 -59
package/lib/esm/Generator.js
CHANGED
|
@@ -1,1155 +1,518 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
import
|
|
9
|
-
import * as changeCase from
|
|
10
|
-
import dayjs from
|
|
11
|
-
import
|
|
12
|
-
|
|
13
|
-
import { ApifoxToYApiData } from './ApifoxToYApiData';
|
|
14
|
-
import { castArray, cloneDeepFast, dedent, groupBy, isEmpty, isFunction, last, memoize, noop, omit, uniq, values } from 'vtils';
|
|
15
|
-
import { Method, RequestBodyType } from './types';
|
|
16
|
-
import { exec } from 'child_process';
|
|
17
|
-
import { getCachedPrettierOptions, getFilteredCat, getNormalizedRelativePath, getPrettier, getRequestDataJsonSchema, getResponseDataJsonSchema, httpGet, jsonSchemaToType, sortByWeights, throwError } from './utils';
|
|
18
|
-
import { SwaggerToYApiServer } from './SwaggerToYApiServer';
|
|
19
|
-
|
|
1
|
+
import { __require } from "./_virtual/_rolldown/runtime.js";
|
|
2
|
+
import { Method, RequestBodyType } from "./types.js";
|
|
3
|
+
import { castArray, cloneDeepFast, dedent, groupBy, isEmpty, isFunction, last, memoize, noop, omit, uniq, values } from "./mini-ut.js";
|
|
4
|
+
import { getCachedPrettierOptions, getFilteredCat, getNormalizedRelativePath, getPrettier, getRequestDataJsonSchema, getResponseDataJsonSchema, httpGet, jsonSchemaToType, sortByWeights, throwError } from "./utils.js";
|
|
5
|
+
import { ApifoxToYApiData } from "./ApifoxToYApiData.js";
|
|
6
|
+
import { SwaggerToYApiServer } from "./SwaggerToYApiServer.js";
|
|
7
|
+
import fs from "fs-extra";
|
|
8
|
+
import path from "path";
|
|
9
|
+
import * as changeCase from "change-case";
|
|
10
|
+
import dayjs from "dayjs";
|
|
11
|
+
import { exec } from "child_process";
|
|
12
|
+
//#region src/Generator.ts
|
|
20
13
|
/**
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
var COMPRESSOR_TREE_SHAKING_ANNOTATION =
|
|
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
|
-
function prepare() {
|
|
212
|
-
return _prepare.apply(this, arguments);
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
return prepare;
|
|
216
|
-
}();
|
|
217
|
-
|
|
218
|
-
_proto.generate = /*#__PURE__*/function () {
|
|
219
|
-
var _generate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10() {
|
|
220
|
-
var _this3 = this;
|
|
221
|
-
|
|
222
|
-
var outputFileList;
|
|
223
|
-
return _regeneratorRuntime.wrap(function _callee10$(_context10) {
|
|
224
|
-
while (1) {
|
|
225
|
-
switch (_context10.prev = _context10.next) {
|
|
226
|
-
case 0:
|
|
227
|
-
outputFileList = Object.create(null);
|
|
228
|
-
_context10.next = 3;
|
|
229
|
-
return Promise.all(this.config.map( /*#__PURE__*/function () {
|
|
230
|
-
var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(serverConfig, serverIndex) {
|
|
231
|
-
var projects;
|
|
232
|
-
return _regeneratorRuntime.wrap(function _callee9$(_context9) {
|
|
233
|
-
while (1) {
|
|
234
|
-
switch (_context9.prev = _context9.next) {
|
|
235
|
-
case 0:
|
|
236
|
-
projects = serverConfig.projects.reduce(function (projects, project) {
|
|
237
|
-
projects.push.apply(projects, castArray(project.token).map(function (token) {
|
|
238
|
-
return _extends({}, project, {
|
|
239
|
-
token: token
|
|
240
|
-
});
|
|
241
|
-
}));
|
|
242
|
-
return projects;
|
|
243
|
-
}, []);
|
|
244
|
-
return _context9.abrupt("return", Promise.all(projects.map( /*#__PURE__*/function () {
|
|
245
|
-
var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(projectConfig, projectIndex) {
|
|
246
|
-
var projectInfo, apifoxInstance;
|
|
247
|
-
return _regeneratorRuntime.wrap(function _callee8$(_context8) {
|
|
248
|
-
while (1) {
|
|
249
|
-
switch (_context8.prev = _context8.next) {
|
|
250
|
-
case 0:
|
|
251
|
-
apifoxInstance = null;
|
|
252
|
-
|
|
253
|
-
if (!(serverConfig.serverType === 'apifox')) {
|
|
254
|
-
_context8.next = 10;
|
|
255
|
-
break;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
if (projectConfig.projectId) {
|
|
259
|
-
_context8.next = 4;
|
|
260
|
-
break;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
throw new Error('projectId is required when serverType is apifox');
|
|
264
|
-
|
|
265
|
-
case 4:
|
|
266
|
-
apifoxInstance = new ApifoxToYApiData({
|
|
267
|
-
token: projectConfig.token,
|
|
268
|
-
projectId: projectConfig.projectId,
|
|
269
|
-
categories: projectConfig.categories,
|
|
270
|
-
serverUrl: serverConfig.serverUrl,
|
|
271
|
-
addFoldersToTags: projectConfig.addFoldersToTags,
|
|
272
|
-
oasVersion: projectConfig.oasVersion,
|
|
273
|
-
exportFormat: projectConfig.exportFormat
|
|
274
|
-
});
|
|
275
|
-
_context8.next = 7;
|
|
276
|
-
return apifoxInstance.getProjectInfo();
|
|
277
|
-
|
|
278
|
-
case 7:
|
|
279
|
-
projectInfo = _context8.sent;
|
|
280
|
-
_context8.next = 13;
|
|
281
|
-
break;
|
|
282
|
-
|
|
283
|
-
case 10:
|
|
284
|
-
_context8.next = 12;
|
|
285
|
-
return _this3.fetchProjectInfo(_extends({}, serverConfig, projectConfig));
|
|
286
|
-
|
|
287
|
-
case 12:
|
|
288
|
-
projectInfo = _context8.sent;
|
|
289
|
-
|
|
290
|
-
case 13:
|
|
291
|
-
_context8.next = 15;
|
|
292
|
-
return Promise.all(projectConfig.categories.map( /*#__PURE__*/function () {
|
|
293
|
-
var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(categoryConfig, categoryIndex) {
|
|
294
|
-
var categoryIds, codes, _iterator, _step, _outputFileList$group, groupedCodes;
|
|
295
|
-
|
|
296
|
-
return _regeneratorRuntime.wrap(function _callee7$(_context7) {
|
|
297
|
-
while (1) {
|
|
298
|
-
switch (_context7.prev = _context7.next) {
|
|
299
|
-
case 0:
|
|
300
|
-
categoryIds = [];
|
|
301
|
-
|
|
302
|
-
if (serverConfig.serverType === 'apifox' && apifoxInstance) {
|
|
303
|
-
categoryIds = apifoxInstance.getCats(categoryConfig);
|
|
304
|
-
} else {
|
|
305
|
-
categoryIds = getFilteredCat(categoryConfig, projectInfo.cats);
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
_context7.next = 4;
|
|
309
|
-
return Promise.all(categoryIds.map( /*#__PURE__*/function () {
|
|
310
|
-
var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(id, categoryIndex2) {
|
|
311
|
-
var syntheticalConfig, interfaceList, interfaceCodes, groupedInterfaceCodes;
|
|
312
|
-
return _regeneratorRuntime.wrap(function _callee6$(_context6) {
|
|
313
|
-
while (1) {
|
|
314
|
-
switch (_context6.prev = _context6.next) {
|
|
315
|
-
case 0:
|
|
316
|
-
categoryConfig = _extends({}, categoryConfig, {
|
|
317
|
-
id: id
|
|
318
|
-
});
|
|
319
|
-
syntheticalConfig = _extends({}, serverConfig, projectConfig, categoryConfig, {
|
|
320
|
-
mockUrl: projectInfo.getMockUrl()
|
|
321
|
-
});
|
|
322
|
-
syntheticalConfig.target = syntheticalConfig.target || 'typescript';
|
|
323
|
-
syntheticalConfig.devUrl = projectInfo.getDevUrl(syntheticalConfig.devEnvName);
|
|
324
|
-
syntheticalConfig.prodUrl = projectInfo.getProdUrl(syntheticalConfig.prodEnvName); // 接口列表
|
|
325
|
-
|
|
326
|
-
// 接口列表
|
|
327
|
-
interfaceList = [];
|
|
328
|
-
|
|
329
|
-
if (!(syntheticalConfig.serverType === 'apifox' && apifoxInstance)) {
|
|
330
|
-
_context6.next = 12;
|
|
331
|
-
break;
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
_context6.next = 9;
|
|
335
|
-
return apifoxInstance.getInterfaceList(syntheticalConfig);
|
|
336
|
-
|
|
337
|
-
case 9:
|
|
338
|
-
interfaceList = _context6.sent;
|
|
339
|
-
_context6.next = 15;
|
|
340
|
-
break;
|
|
341
|
-
|
|
342
|
-
case 12:
|
|
343
|
-
_context6.next = 14;
|
|
344
|
-
return _this3.fetchInterfaceList(syntheticalConfig);
|
|
345
|
-
|
|
346
|
-
case 14:
|
|
347
|
-
interfaceList = _context6.sent;
|
|
348
|
-
|
|
349
|
-
case 15:
|
|
350
|
-
interfaceList = interfaceList.map(function (interfaceInfo) {
|
|
351
|
-
// 实现 _project 字段
|
|
352
|
-
interfaceInfo._project = omit(projectInfo, ['cats', 'getMockUrl', 'getDevUrl', 'getProdUrl']); // 预处理
|
|
353
|
-
|
|
354
|
-
// 预处理
|
|
355
|
-
var _interfaceInfo = isFunction(syntheticalConfig.preproccessInterface) ? syntheticalConfig.preproccessInterface(cloneDeepFast(interfaceInfo), changeCase, syntheticalConfig) : interfaceInfo;
|
|
356
|
-
|
|
357
|
-
return _interfaceInfo;
|
|
358
|
-
}).filter(Boolean);
|
|
359
|
-
interfaceList.sort(function (a, b) {
|
|
360
|
-
return a._id - b._id;
|
|
361
|
-
});
|
|
362
|
-
_context6.next = 19;
|
|
363
|
-
return Promise.all(interfaceList.map( /*#__PURE__*/function () {
|
|
364
|
-
var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(interfaceInfo) {
|
|
365
|
-
var outputFilePath, categoryUID, code, weights;
|
|
366
|
-
return _regeneratorRuntime.wrap(function _callee5$(_context5) {
|
|
367
|
-
while (1) {
|
|
368
|
-
switch (_context5.prev = _context5.next) {
|
|
369
|
-
case 0:
|
|
370
|
-
outputFilePath = path.resolve(_this3.options.cwd, typeof syntheticalConfig.outputFilePath === 'function' ? syntheticalConfig.outputFilePath(interfaceInfo, changeCase) : syntheticalConfig.outputFilePath);
|
|
371
|
-
categoryUID = "_" + serverIndex + "_" + projectIndex + "_" + categoryIndex + "_" + categoryIndex2;
|
|
372
|
-
_context5.next = 4;
|
|
373
|
-
return _this3.generateInterfaceCode(syntheticalConfig, interfaceInfo, categoryUID);
|
|
374
|
-
|
|
375
|
-
case 4:
|
|
376
|
-
code = _context5.sent;
|
|
377
|
-
weights = [serverIndex, projectIndex, categoryIndex, categoryIndex2];
|
|
378
|
-
return _context5.abrupt("return", {
|
|
379
|
-
categoryUID: categoryUID,
|
|
380
|
-
outputFilePath: outputFilePath,
|
|
381
|
-
weights: weights,
|
|
382
|
-
code: code
|
|
383
|
-
});
|
|
384
|
-
|
|
385
|
-
case 7:
|
|
386
|
-
case "end":
|
|
387
|
-
return _context5.stop();
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
}, _callee5);
|
|
391
|
-
}));
|
|
392
|
-
|
|
393
|
-
return function (_x12) {
|
|
394
|
-
return _ref12.apply(this, arguments);
|
|
395
|
-
};
|
|
396
|
-
}()));
|
|
397
|
-
|
|
398
|
-
case 19:
|
|
399
|
-
interfaceCodes = _context6.sent;
|
|
400
|
-
groupedInterfaceCodes = groupBy(interfaceCodes, function (item) {
|
|
401
|
-
return item.outputFilePath;
|
|
402
|
-
});
|
|
403
|
-
return _context6.abrupt("return", Object.keys(groupedInterfaceCodes).map(function (outputFilePath) {
|
|
404
|
-
var categoryCode = [].concat(uniq(sortByWeights(groupedInterfaceCodes[outputFilePath]).map(function (item) {
|
|
405
|
-
return item.categoryUID;
|
|
406
|
-
})).map(function (categoryUID) {
|
|
407
|
-
if (syntheticalConfig.typesOnly) return '';
|
|
408
|
-
var text = '';
|
|
409
|
-
|
|
410
|
-
if (syntheticalConfig.withoutUrl !== true) {
|
|
411
|
-
text += "const devUrl" + categoryUID + " = " + JSON.stringify(syntheticalConfig.devUrl) + " as any;\n const mockUrl" + categoryUID + " = " + JSON.stringify(syntheticalConfig.mockUrl) + " as any;\n const prodUrl" + categoryUID + " = " + JSON.stringify(syntheticalConfig.prodUrl) + " as any;";
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
if (syntheticalConfig.ignoreUselessConfigVar !== true) {
|
|
415
|
-
text += "const dataKey" + categoryUID + " = " + JSON.stringify(syntheticalConfig.dataKey) + " as any;";
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
return dedent(text);
|
|
419
|
-
}), sortByWeights(groupedInterfaceCodes[outputFilePath]).map(function (item) {
|
|
420
|
-
return item.code;
|
|
421
|
-
})).filter(Boolean).join('\n\n');
|
|
422
|
-
|
|
423
|
-
if (!outputFileList[outputFilePath]) {
|
|
424
|
-
outputFileList[outputFilePath] = {
|
|
425
|
-
syntheticalConfig: syntheticalConfig,
|
|
426
|
-
content: [],
|
|
427
|
-
requestFunctionFilePath: syntheticalConfig.requestFunctionFilePath ? path.resolve(_this3.options.cwd, syntheticalConfig.requestFunctionFilePath) : path.join(path.dirname(outputFilePath), 'request.ts'),
|
|
428
|
-
requestHookMakerFilePath: syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled ? syntheticalConfig.reactHooks.requestHookMakerFilePath ? path.resolve(_this3.options.cwd, syntheticalConfig.reactHooks.requestHookMakerFilePath) : path.join(path.dirname(outputFilePath), 'makeRequestHook.ts') : ''
|
|
429
|
-
};
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
return {
|
|
433
|
-
outputFilePath: outputFilePath,
|
|
434
|
-
code: categoryCode,
|
|
435
|
-
weights: last(sortByWeights(groupedInterfaceCodes[outputFilePath])).weights
|
|
436
|
-
};
|
|
437
|
-
}));
|
|
438
|
-
|
|
439
|
-
case 22:
|
|
440
|
-
case "end":
|
|
441
|
-
return _context6.stop();
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
}, _callee6);
|
|
445
|
-
}));
|
|
446
|
-
|
|
447
|
-
return function (_x10, _x11) {
|
|
448
|
-
return _ref11.apply(this, arguments);
|
|
449
|
-
};
|
|
450
|
-
}()));
|
|
451
|
-
|
|
452
|
-
case 4:
|
|
453
|
-
codes = _context7.sent.flat();
|
|
454
|
-
|
|
455
|
-
for (_iterator = _createForOfIteratorHelperLoose(values(groupBy(codes, function (item) {
|
|
456
|
-
return item.outputFilePath;
|
|
457
|
-
}))); !(_step = _iterator()).done;) {
|
|
458
|
-
groupedCodes = _step.value;
|
|
459
|
-
sortByWeights(groupedCodes);
|
|
460
|
-
|
|
461
|
-
(_outputFileList$group = outputFileList[groupedCodes[0].outputFilePath].content).push.apply(_outputFileList$group, groupedCodes.map(function (item) {
|
|
462
|
-
return item.code;
|
|
463
|
-
}));
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
case 6:
|
|
467
|
-
case "end":
|
|
468
|
-
return _context7.stop();
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
}, _callee7);
|
|
472
|
-
}));
|
|
473
|
-
|
|
474
|
-
return function (_x8, _x9) {
|
|
475
|
-
return _ref10.apply(this, arguments);
|
|
476
|
-
};
|
|
477
|
-
}()));
|
|
478
|
-
|
|
479
|
-
case 15:
|
|
480
|
-
case "end":
|
|
481
|
-
return _context8.stop();
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
}, _callee8);
|
|
485
|
-
}));
|
|
486
|
-
|
|
487
|
-
return function (_x6, _x7) {
|
|
488
|
-
return _ref9.apply(this, arguments);
|
|
489
|
-
};
|
|
490
|
-
}())));
|
|
491
|
-
|
|
492
|
-
case 2:
|
|
493
|
-
case "end":
|
|
494
|
-
return _context9.stop();
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
}, _callee9);
|
|
498
|
-
}));
|
|
499
|
-
|
|
500
|
-
return function (_x4, _x5) {
|
|
501
|
-
return _ref8.apply(this, arguments);
|
|
502
|
-
};
|
|
503
|
-
}()));
|
|
504
|
-
|
|
505
|
-
case 3:
|
|
506
|
-
return _context10.abrupt("return", outputFileList);
|
|
507
|
-
|
|
508
|
-
case 4:
|
|
509
|
-
case "end":
|
|
510
|
-
return _context10.stop();
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
}, _callee10, this);
|
|
514
|
-
}));
|
|
515
|
-
|
|
516
|
-
function generate() {
|
|
517
|
-
return _generate.apply(this, arguments);
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
return generate;
|
|
521
|
-
}();
|
|
522
|
-
|
|
523
|
-
_proto.write = /*#__PURE__*/function () {
|
|
524
|
-
var _write = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(outputFileList) {
|
|
525
|
-
var _this4 = this;
|
|
526
|
-
|
|
527
|
-
return _regeneratorRuntime.wrap(function _callee12$(_context12) {
|
|
528
|
-
while (1) {
|
|
529
|
-
switch (_context12.prev = _context12.next) {
|
|
530
|
-
case 0:
|
|
531
|
-
return _context12.abrupt("return", Promise.all(Object.keys(outputFileList).map( /*#__PURE__*/function () {
|
|
532
|
-
var _ref13 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(outputFilePath) {
|
|
533
|
-
var _outputFileList$outpu, content, requestFunctionFilePath, requestHookMakerFilePath, syntheticalConfig, rawRequestFunctionFilePath, rawRequestHookMakerFilePath, rawOutputContent, prettier, prettyOutputContent, outputContent;
|
|
534
|
-
|
|
535
|
-
return _regeneratorRuntime.wrap(function _callee11$(_context11) {
|
|
536
|
-
while (1) {
|
|
537
|
-
switch (_context11.prev = _context11.next) {
|
|
538
|
-
case 0:
|
|
539
|
-
_outputFileList$outpu = outputFileList[outputFilePath], content = _outputFileList$outpu.content, requestFunctionFilePath = _outputFileList$outpu.requestFunctionFilePath, requestHookMakerFilePath = _outputFileList$outpu.requestHookMakerFilePath, syntheticalConfig = _outputFileList$outpu.syntheticalConfig;
|
|
540
|
-
rawRequestFunctionFilePath = requestFunctionFilePath;
|
|
541
|
-
rawRequestHookMakerFilePath = requestHookMakerFilePath; // 支持 .jsx? 后缀
|
|
542
|
-
|
|
543
|
-
// 支持 .jsx? 后缀
|
|
544
|
-
outputFilePath = outputFilePath.replace(/\.js(x)?$/, '.ts$1');
|
|
545
|
-
requestFunctionFilePath = requestFunctionFilePath.replace(/\.js(x)?$/, '.ts$1');
|
|
546
|
-
requestHookMakerFilePath = requestHookMakerFilePath.replace(/\.js(x)?$/, '.ts$1');
|
|
547
|
-
|
|
548
|
-
if (syntheticalConfig.typesOnly) {
|
|
549
|
-
_context11.next = 20;
|
|
550
|
-
break;
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
_context11.next = 9;
|
|
554
|
-
return fs.pathExists(rawRequestFunctionFilePath);
|
|
555
|
-
|
|
556
|
-
case 9:
|
|
557
|
-
if (_context11.sent) {
|
|
558
|
-
_context11.next = 12;
|
|
559
|
-
break;
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
_context11.next = 12;
|
|
563
|
-
return fs.outputFile(requestFunctionFilePath, dedent(_templateObject || (_templateObject = _taggedTemplateLiteralLoose(["\n import type { RequestFunctionParams } from 'yapi-apifox-to-typescript'\n\n export interface RequestOptions {\n /**\n * \u4F7F\u7528\u7684\u670D\u52A1\u5668\u3002\n *\n * - `prod`: \u751F\u4EA7\u670D\u52A1\u5668\n * - `dev`: \u6D4B\u8BD5\u670D\u52A1\u5668\n * - `mock`: \u6A21\u62DF\u670D\u52A1\u5668\n *\n * @default prod\n */\n server?: 'prod' | 'dev' | 'mock',\n }\n\n export default function request<TResponseData>(\n payload: RequestFunctionParams,\n options: RequestOptions = {\n server: 'prod',\n },\n ): Promise<TResponseData> {\n return new Promise<TResponseData>((resolve, reject) => {\n // \u57FA\u672C\u5730\u5740\n ", "\n\n // \u8BF7\u6C42\u5730\u5740\n const url = `${baseUrl}${payload.path}`\n\n // \u5177\u4F53\u8BF7\u6C42\u903B\u8F91\n })\n }\n "], ["\n import type { RequestFunctionParams } from 'yapi-apifox-to-typescript'\n\n export interface RequestOptions {\n /**\n * \u4F7F\u7528\u7684\u670D\u52A1\u5668\u3002\n *\n * - \\`prod\\`: \u751F\u4EA7\u670D\u52A1\u5668\n * - \\`dev\\`: \u6D4B\u8BD5\u670D\u52A1\u5668\n * - \\`mock\\`: \u6A21\u62DF\u670D\u52A1\u5668\n *\n * @default prod\n */\n server?: 'prod' | 'dev' | 'mock',\n }\n\n export default function request<TResponseData>(\n payload: RequestFunctionParams,\n options: RequestOptions = {\n server: 'prod',\n },\n ): Promise<TResponseData> {\n return new Promise<TResponseData>((resolve, reject) => {\n // \u57FA\u672C\u5730\u5740\n ", "\n\n // \u8BF7\u6C42\u5730\u5740\n const url = \\`\\${baseUrl}\\${payload.path}\\`\n\n // \u5177\u4F53\u8BF7\u6C42\u903B\u8F91\n })\n }\n "])), syntheticalConfig.withoutUrl ? "const baseUrl = ''" : " const baseUrl = options.server === 'mock'\n ? payload.mockUrl\n : options.server === 'dev'\n ? payload.devUrl\n : payload.prodUrl"));
|
|
564
|
-
|
|
565
|
-
case 12:
|
|
566
|
-
_context11.t0 = syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled;
|
|
567
|
-
|
|
568
|
-
if (!_context11.t0) {
|
|
569
|
-
_context11.next = 17;
|
|
570
|
-
break;
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
_context11.next = 16;
|
|
574
|
-
return fs.pathExists(rawRequestHookMakerFilePath);
|
|
575
|
-
|
|
576
|
-
case 16:
|
|
577
|
-
_context11.t0 = !_context11.sent;
|
|
578
|
-
|
|
579
|
-
case 17:
|
|
580
|
-
if (!_context11.t0) {
|
|
581
|
-
_context11.next = 20;
|
|
582
|
-
break;
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
_context11.next = 20;
|
|
586
|
-
return fs.outputFile(requestHookMakerFilePath, dedent(_templateObject2 || (_templateObject2 = _taggedTemplateLiteralLoose(["\n import { useState, useEffect } from 'react'\n import type { RequestConfig } from 'yapi-apifox-to-typescript'\n import type { Request } from ", "\n import baseRequest from ", "\n\n export default function makeRequestHook<TRequestData, TRequestConfig extends RequestConfig, TRequestResult extends ReturnType<typeof baseRequest>>(request: Request<TRequestData, TRequestConfig, TRequestResult>) {\n type Data = TRequestResult extends Promise<infer R> ? R : TRequestResult\n return function useRequest(requestData: TRequestData) {\n // \u4E00\u4E2A\u7B80\u5355\u7684 Hook \u5B9E\u73B0\uFF0C\u5B9E\u9645\u9879\u76EE\u53EF\u7ED3\u5408\u5176\u4ED6\u5E93\u4F7F\u7528\uFF0C\u6BD4\u5982\uFF1A\n // @umijs/hooks \u7684 useRequest (https://github.com/umijs/hooks)\n // swr (https://github.com/zeit/swr)\n\n const [loading, setLoading] = useState(true)\n const [data, setData] = useState<Data>()\n\n useEffect(() => {\n request(requestData).then(data => {\n setLoading(false)\n setData(data as any)\n })\n }, [JSON.stringify(requestData)])\n\n return {\n loading,\n data,\n }\n }\n }\n "])), JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, outputFilePath)), JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, requestFunctionFilePath))));
|
|
587
|
-
|
|
588
|
-
case 20:
|
|
589
|
-
// 始终写入主文件
|
|
590
|
-
rawOutputContent = dedent(_templateObject3 || (_templateObject3 = _taggedTemplateLiteralLoose(["\n /* tslint:disable */\n /* eslint-disable */\n\n /* \u8BE5\u6587\u4EF6\u7531 yapi-apifox-to-typescript \u81EA\u52A8\u751F\u6210\uFF0C\u8BF7\u52FF\u76F4\u63A5\u4FEE\u6539\uFF01\uFF01\uFF01 */\n\n ", "\n "])), syntheticalConfig.typesOnly ? dedent(_templateObject4 || (_templateObject4 = _taggedTemplateLiteralLoose(["\n // @ts-ignore\n type FileData = File\n\n ", "\n "])), content.join('\n\n').trim()) : dedent(_templateObject5 || (_templateObject5 = _taggedTemplateLiteralLoose(["\n // @ts-ignore\n // prettier-ignore\n import { QueryStringArrayFormat, Method, RequestBodyType, ", "FileData, prepare } from 'yapi-apifox-to-typescript'\n // @ts-ignore\n // prettier-ignore\n import type { RequestConfig, RequestFunctionRestArgs } from 'yapi-apifox-to-typescript'\n // @ts-ignore\n import request from ", "\n ", "\n\n type UserRequestRestArgs = RequestFunctionRestArgs<typeof request>\n\n // Request: \u76EE\u524D React Hooks \u529F\u80FD\u6709\u7528\u5230\n export type Request<TRequestData, TRequestConfig extends RequestConfig, TRequestResult> = (\n TRequestConfig['requestDataOptional'] extends true\n ? (requestData?: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult\n : (requestData: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult\n ) & {\n requestConfig: TRequestConfig\n }\n\n ", "\n "])), syntheticalConfig.ignoreUselessConfigVar ? "" : "ResponseBodyType, ", JSON.stringify(getNormalizedRelativePath(outputFilePath, requestFunctionFilePath)), !syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? '' : dedent(_templateObject6 || (_templateObject6 = _taggedTemplateLiteralLoose(["\n // @ts-ignore\n import makeRequestHook from ", "\n "])), JSON.stringify(getNormalizedRelativePath(outputFilePath, requestHookMakerFilePath))), content.join('\n\n').trim())); // ref: https://prettier.io/docs/en/options.html
|
|
591
|
-
|
|
592
|
-
_context11.next = 23;
|
|
593
|
-
return getPrettier(_this4.options.cwd);
|
|
594
|
-
|
|
595
|
-
case 23:
|
|
596
|
-
prettier = _context11.sent;
|
|
597
|
-
_context11.t1 = prettier;
|
|
598
|
-
_context11.t2 = rawOutputContent;
|
|
599
|
-
_context11.t3 = _extends;
|
|
600
|
-
_context11.t4 = {};
|
|
601
|
-
_context11.next = 30;
|
|
602
|
-
return getCachedPrettierOptions();
|
|
603
|
-
|
|
604
|
-
case 30:
|
|
605
|
-
_context11.t5 = _context11.sent;
|
|
606
|
-
_context11.t6 = {
|
|
607
|
-
filepath: outputFilePath
|
|
608
|
-
};
|
|
609
|
-
_context11.t7 = (0, _context11.t3)(_context11.t4, _context11.t5, _context11.t6);
|
|
610
|
-
_context11.next = 35;
|
|
611
|
-
return _context11.t1.format.call(_context11.t1, _context11.t2, _context11.t7);
|
|
612
|
-
|
|
613
|
-
case 35:
|
|
614
|
-
prettyOutputContent = _context11.sent;
|
|
615
|
-
outputContent = dedent(_templateObject7 || (_templateObject7 = _taggedTemplateLiteralLoose(["\n /* prettier-ignore-start */\n ", "\n /* prettier-ignore-end */\n "])), prettyOutputContent) + "\n";
|
|
616
|
-
_context11.next = 39;
|
|
617
|
-
return fs.outputFile(outputFilePath, outputContent);
|
|
618
|
-
|
|
619
|
-
case 39:
|
|
620
|
-
if (!(syntheticalConfig.target === 'javascript')) {
|
|
621
|
-
_context11.next = 44;
|
|
622
|
-
break;
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
_context11.next = 42;
|
|
626
|
-
return _this4.tsc(outputFilePath);
|
|
627
|
-
|
|
628
|
-
case 42:
|
|
629
|
-
_context11.next = 44;
|
|
630
|
-
return Promise.all([fs.remove(requestFunctionFilePath).catch(noop), fs.remove(requestHookMakerFilePath).catch(noop), fs.remove(outputFilePath).catch(noop)]);
|
|
631
|
-
|
|
632
|
-
case 44:
|
|
633
|
-
case "end":
|
|
634
|
-
return _context11.stop();
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
}, _callee11);
|
|
638
|
-
}));
|
|
639
|
-
|
|
640
|
-
return function (_x14) {
|
|
641
|
-
return _ref13.apply(this, arguments);
|
|
642
|
-
};
|
|
643
|
-
}())));
|
|
644
|
-
|
|
645
|
-
case 1:
|
|
646
|
-
case "end":
|
|
647
|
-
return _context12.stop();
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
}, _callee12);
|
|
651
|
-
}));
|
|
652
|
-
|
|
653
|
-
function write(_x13) {
|
|
654
|
-
return _write.apply(this, arguments);
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
return write;
|
|
658
|
-
}();
|
|
659
|
-
|
|
660
|
-
_proto.tsc = /*#__PURE__*/function () {
|
|
661
|
-
var _tsc = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(file) {
|
|
662
|
-
var _this5 = this;
|
|
663
|
-
|
|
664
|
-
return _regeneratorRuntime.wrap(function _callee13$(_context13) {
|
|
665
|
-
while (1) {
|
|
666
|
-
switch (_context13.prev = _context13.next) {
|
|
667
|
-
case 0:
|
|
668
|
-
return _context13.abrupt("return", new Promise(function (resolve) {
|
|
669
|
-
// add this to fix bug that not-generator-file-on-window
|
|
670
|
-
var command = "" + (require('os').platform() === 'win32' ? 'node ' : '') + JSON.stringify(require.resolve("typescript/bin/tsc"));
|
|
671
|
-
exec(command + " --target ES2019 --module ESNext --jsx preserve --declaration --esModuleInterop " + JSON.stringify(file), {
|
|
672
|
-
cwd: _this5.options.cwd,
|
|
673
|
-
env: process.env
|
|
674
|
-
}, function () {
|
|
675
|
-
return resolve();
|
|
676
|
-
});
|
|
677
|
-
}));
|
|
678
|
-
|
|
679
|
-
case 1:
|
|
680
|
-
case "end":
|
|
681
|
-
return _context13.stop();
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
}, _callee13);
|
|
685
|
-
}));
|
|
686
|
-
|
|
687
|
-
function tsc(_x15) {
|
|
688
|
-
return _tsc.apply(this, arguments);
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
return tsc;
|
|
692
|
-
}();
|
|
693
|
-
|
|
694
|
-
_proto.fetchApi = /*#__PURE__*/function () {
|
|
695
|
-
var _fetchApi = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(url, query) {
|
|
696
|
-
var res;
|
|
697
|
-
return _regeneratorRuntime.wrap(function _callee14$(_context14) {
|
|
698
|
-
while (1) {
|
|
699
|
-
switch (_context14.prev = _context14.next) {
|
|
700
|
-
case 0:
|
|
701
|
-
_context14.next = 2;
|
|
702
|
-
return httpGet(url, query);
|
|
703
|
-
|
|
704
|
-
case 2:
|
|
705
|
-
res = _context14.sent;
|
|
706
|
-
|
|
707
|
-
/* istanbul ignore next */
|
|
708
|
-
if (res && res.errcode) {
|
|
709
|
-
throwError(res.errmsg + " [\u8BF7\u6C42\u5730\u5740: " + url + "] [\u8BF7\u6C42\u53C2\u6570: " + new URLSearchParams(query).toString() + "]");
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
return _context14.abrupt("return", res.data || res);
|
|
713
|
-
|
|
714
|
-
case 5:
|
|
715
|
-
case "end":
|
|
716
|
-
return _context14.stop();
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
}, _callee14);
|
|
720
|
-
}));
|
|
721
|
-
|
|
722
|
-
function fetchApi(_x16, _x17) {
|
|
723
|
-
return _fetchApi.apply(this, arguments);
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
return fetchApi;
|
|
727
|
-
}();
|
|
728
|
-
|
|
729
|
-
/** 获取分类的接口列表 */
|
|
730
|
-
_proto.fetchInterfaceList =
|
|
731
|
-
/*#__PURE__*/
|
|
732
|
-
function () {
|
|
733
|
-
var _fetchInterfaceList = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(_ref14) {
|
|
734
|
-
var serverUrl, token, id, category;
|
|
735
|
-
return _regeneratorRuntime.wrap(function _callee15$(_context15) {
|
|
736
|
-
while (1) {
|
|
737
|
-
switch (_context15.prev = _context15.next) {
|
|
738
|
-
case 0:
|
|
739
|
-
serverUrl = _ref14.serverUrl, token = _ref14.token, id = _ref14.id;
|
|
740
|
-
_context15.next = 3;
|
|
741
|
-
return this.fetchExport({
|
|
742
|
-
serverUrl: serverUrl,
|
|
743
|
-
token: token
|
|
744
|
-
});
|
|
745
|
-
|
|
746
|
-
case 3:
|
|
747
|
-
_context15.t0 = _context15.sent;
|
|
748
|
-
|
|
749
|
-
if (_context15.t0) {
|
|
750
|
-
_context15.next = 6;
|
|
751
|
-
break;
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
_context15.t0 = [];
|
|
755
|
-
|
|
756
|
-
case 6:
|
|
757
|
-
category = _context15.t0.find(function (cat) {
|
|
758
|
-
return !isEmpty(cat) && !isEmpty(cat.list) && cat.list[0].catid === id;
|
|
759
|
-
});
|
|
760
|
-
|
|
761
|
-
if (category) {
|
|
762
|
-
category.list.forEach(function (interfaceInfo) {
|
|
763
|
-
// 实现 _category 字段
|
|
764
|
-
interfaceInfo._category = omit(category, ['list']);
|
|
765
|
-
});
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
return _context15.abrupt("return", category ? category.list : []);
|
|
769
|
-
|
|
770
|
-
case 9:
|
|
771
|
-
case "end":
|
|
772
|
-
return _context15.stop();
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
}, _callee15, this);
|
|
776
|
-
}));
|
|
777
|
-
|
|
778
|
-
function fetchInterfaceList(_x18) {
|
|
779
|
-
return _fetchInterfaceList.apply(this, arguments);
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
return fetchInterfaceList;
|
|
783
|
-
}()
|
|
784
|
-
/** 获取项目信息 */
|
|
785
|
-
;
|
|
786
|
-
|
|
787
|
-
_proto.fetchProjectInfo =
|
|
788
|
-
/*#__PURE__*/
|
|
789
|
-
function () {
|
|
790
|
-
var _fetchProjectInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee16(syntheticalConfig) {
|
|
791
|
-
var projectInfo, projectCats;
|
|
792
|
-
return _regeneratorRuntime.wrap(function _callee16$(_context16) {
|
|
793
|
-
while (1) {
|
|
794
|
-
switch (_context16.prev = _context16.next) {
|
|
795
|
-
case 0:
|
|
796
|
-
_context16.next = 2;
|
|
797
|
-
return this.fetchProject(syntheticalConfig);
|
|
798
|
-
|
|
799
|
-
case 2:
|
|
800
|
-
projectInfo = _context16.sent;
|
|
801
|
-
_context16.next = 5;
|
|
802
|
-
return this.fetchApi(syntheticalConfig.serverUrl + "/api/interface/getCatMenu", {
|
|
803
|
-
token: syntheticalConfig.token,
|
|
804
|
-
project_id: projectInfo._id
|
|
805
|
-
});
|
|
806
|
-
|
|
807
|
-
case 5:
|
|
808
|
-
projectCats = _context16.sent;
|
|
809
|
-
return _context16.abrupt("return", _extends({}, projectInfo, {
|
|
810
|
-
cats: projectCats,
|
|
811
|
-
getMockUrl: function getMockUrl() {
|
|
812
|
-
return syntheticalConfig.serverUrl + "/mock/" + projectInfo._id;
|
|
813
|
-
},
|
|
814
|
-
getDevUrl: function getDevUrl(devEnvName) {
|
|
815
|
-
var env = projectInfo.env.find(function (e) {
|
|
816
|
-
return e.name === devEnvName;
|
|
817
|
-
});
|
|
818
|
-
return env && env.domain
|
|
819
|
-
/* istanbul ignore next */
|
|
820
|
-
|| '';
|
|
821
|
-
},
|
|
822
|
-
getProdUrl: function getProdUrl(prodEnvName) {
|
|
823
|
-
var env = projectInfo.env.find(function (e) {
|
|
824
|
-
return e.name === prodEnvName;
|
|
825
|
-
});
|
|
826
|
-
return env && env.domain
|
|
827
|
-
/* istanbul ignore next */
|
|
828
|
-
|| '';
|
|
14
|
+
* @see https://webpack.js.org/guides/tree-shaking/#mark-a-function-call-as-side-effect-free
|
|
15
|
+
* @see https://terser.org/docs/api-reference.html#annotations
|
|
16
|
+
*/
|
|
17
|
+
var COMPRESSOR_TREE_SHAKING_ANNOTATION = "/*#__PURE__*/";
|
|
18
|
+
var Generator = class {
|
|
19
|
+
constructor(config, options = { cwd: process.cwd() }) {
|
|
20
|
+
this.options = options;
|
|
21
|
+
this.config = [];
|
|
22
|
+
this.disposes = [];
|
|
23
|
+
this.barrelOutputMap = /* @__PURE__ */ new Map();
|
|
24
|
+
this.fetchProject = memoize(async ({ serverUrl, token }) => {
|
|
25
|
+
const projectInfo = await this.fetchApi(`${serverUrl}/api/project/get`, { token });
|
|
26
|
+
projectInfo.basepath = `/${projectInfo.basepath || "/"}`.replace(/\/+$/, "").replace(/^\/+/, "/");
|
|
27
|
+
projectInfo._url = `${serverUrl}/project/${projectInfo._id}/interface/api`;
|
|
28
|
+
return projectInfo;
|
|
29
|
+
}, ({ serverUrl, token }) => `${serverUrl}|${token}`);
|
|
30
|
+
this.fetchExport = memoize(async ({ serverUrl, token }) => {
|
|
31
|
+
const projectInfo = await this.fetchProject({
|
|
32
|
+
serverUrl,
|
|
33
|
+
token
|
|
34
|
+
});
|
|
35
|
+
return (await this.fetchApi(`${serverUrl}/api/plugin/export`, {
|
|
36
|
+
type: "json",
|
|
37
|
+
status: "all",
|
|
38
|
+
isWiki: "false",
|
|
39
|
+
token
|
|
40
|
+
})).map((cat) => {
|
|
41
|
+
const projectId = cat.list?.[0]?.project_id || 0;
|
|
42
|
+
cat._url = `${serverUrl}/project/${projectId}/interface/api/cat_${cat.list?.[0]?.catid || 0}`;
|
|
43
|
+
cat.list = (cat.list || []).map((item) => {
|
|
44
|
+
const interfaceId = item._id;
|
|
45
|
+
item._url = `${serverUrl}/project/${projectId}/interface/api/${interfaceId}`;
|
|
46
|
+
item.path = `${projectInfo.basepath}${item.path}`;
|
|
47
|
+
return item;
|
|
48
|
+
});
|
|
49
|
+
return cat;
|
|
50
|
+
});
|
|
51
|
+
}, ({ serverUrl, token }) => `${serverUrl}|${token}`);
|
|
52
|
+
this.config = castArray(config);
|
|
53
|
+
}
|
|
54
|
+
async prepare() {
|
|
55
|
+
this.config = await Promise.all(this.config.map(async (item) => {
|
|
56
|
+
if (item.serverType === "swagger" || item.serverType === "local") {
|
|
57
|
+
const swaggerToYApiServer = new SwaggerToYApiServer(item.serverType === "local" ? { swaggerJsonPath: path.isAbsolute(item.serverUrl || "") ? item.serverUrl : path.resolve(this.options.cwd, item.serverUrl || "") } : { swaggerJsonUrl: item.serverUrl });
|
|
58
|
+
item.serverUrl = await swaggerToYApiServer.start();
|
|
59
|
+
this.disposes.push(() => swaggerToYApiServer.stop());
|
|
60
|
+
}
|
|
61
|
+
if (item.serverUrl) item.serverUrl = item.serverUrl.replace(/\/+$/, "");
|
|
62
|
+
return item;
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
async generate() {
|
|
66
|
+
const outputFileList = Object.create(null);
|
|
67
|
+
await Promise.all(this.config.map(async (serverConfig, serverIndex) => {
|
|
68
|
+
const projects = serverConfig.projects.reduce((projects, project) => {
|
|
69
|
+
projects.push(...castArray(project.token).map((token) => ({
|
|
70
|
+
...project,
|
|
71
|
+
token
|
|
72
|
+
})));
|
|
73
|
+
return projects;
|
|
74
|
+
}, []);
|
|
75
|
+
return Promise.all(projects.map(async (projectConfig, projectIndex) => {
|
|
76
|
+
let projectInfo;
|
|
77
|
+
let apifoxInstance = null;
|
|
78
|
+
if (serverConfig.serverType === "apifox") {
|
|
79
|
+
if (!projectConfig.projectId) throw new Error("projectId is required when serverType is apifox");
|
|
80
|
+
apifoxInstance = new ApifoxToYApiData({
|
|
81
|
+
token: projectConfig.token,
|
|
82
|
+
projectId: projectConfig.projectId,
|
|
83
|
+
categories: projectConfig.categories,
|
|
84
|
+
serverUrl: serverConfig.serverUrl,
|
|
85
|
+
addFoldersToTags: projectConfig.addFoldersToTags,
|
|
86
|
+
oasVersion: projectConfig.oasVersion,
|
|
87
|
+
exportFormat: projectConfig.exportFormat
|
|
88
|
+
});
|
|
89
|
+
projectInfo = await apifoxInstance.getProjectInfo();
|
|
90
|
+
} else projectInfo = await this.fetchProjectInfo({
|
|
91
|
+
...serverConfig,
|
|
92
|
+
...projectConfig
|
|
93
|
+
});
|
|
94
|
+
await Promise.all(projectConfig.categories.map(async (categoryConfig, categoryIndex) => {
|
|
95
|
+
let categoryIds = [];
|
|
96
|
+
if (serverConfig.serverType === "apifox" && apifoxInstance) categoryIds = apifoxInstance.getCats(categoryConfig);
|
|
97
|
+
else categoryIds = getFilteredCat(categoryConfig, projectInfo.cats);
|
|
98
|
+
const codes = (await Promise.all(categoryIds.map(async (id, categoryIndex2) => {
|
|
99
|
+
categoryConfig = {
|
|
100
|
+
...categoryConfig,
|
|
101
|
+
id
|
|
102
|
+
};
|
|
103
|
+
const syntheticalConfig = {
|
|
104
|
+
...serverConfig,
|
|
105
|
+
...projectConfig,
|
|
106
|
+
...categoryConfig,
|
|
107
|
+
mockUrl: projectInfo.getMockUrl()
|
|
108
|
+
};
|
|
109
|
+
syntheticalConfig.target = syntheticalConfig.target || "typescript";
|
|
110
|
+
syntheticalConfig.devUrl = projectInfo.getDevUrl(syntheticalConfig.devEnvName);
|
|
111
|
+
syntheticalConfig.prodUrl = projectInfo.getProdUrl(syntheticalConfig.prodEnvName);
|
|
112
|
+
let interfaceList = [];
|
|
113
|
+
if (syntheticalConfig.serverType === "apifox" && apifoxInstance) interfaceList = await apifoxInstance.getInterfaceList(syntheticalConfig);
|
|
114
|
+
else interfaceList = await this.fetchInterfaceList(syntheticalConfig);
|
|
115
|
+
interfaceList = interfaceList.map((interfaceInfo) => {
|
|
116
|
+
interfaceInfo._project = omit(projectInfo, [
|
|
117
|
+
"cats",
|
|
118
|
+
"getMockUrl",
|
|
119
|
+
"getDevUrl",
|
|
120
|
+
"getProdUrl"
|
|
121
|
+
]);
|
|
122
|
+
return isFunction(syntheticalConfig.preproccessInterface) ? syntheticalConfig.preproccessInterface(cloneDeepFast(interfaceInfo), changeCase, syntheticalConfig) : interfaceInfo;
|
|
123
|
+
}).filter(Boolean);
|
|
124
|
+
interfaceList.sort((a, b) => a._id - b._id);
|
|
125
|
+
const interfaceCodes = await Promise.all(interfaceList.map(async (interfaceInfo) => {
|
|
126
|
+
const baseOutputFilePath = path.resolve(this.options.cwd, typeof syntheticalConfig.outputFilePath === "function" ? syntheticalConfig.outputFilePath(interfaceInfo, changeCase) : syntheticalConfig.outputFilePath);
|
|
127
|
+
let outputFilePath = baseOutputFilePath;
|
|
128
|
+
if (syntheticalConfig.splitByModule) {
|
|
129
|
+
const moduleName = interfaceInfo.path.split("/").filter(Boolean)[0] || "default";
|
|
130
|
+
outputFilePath = path.join(path.dirname(baseOutputFilePath), "modules", `${moduleName}.ts`);
|
|
131
|
+
this.barrelOutputMap.set(baseOutputFilePath, true);
|
|
132
|
+
}
|
|
133
|
+
const categoryUID = `_${serverIndex}_${projectIndex}_${categoryIndex}_${categoryIndex2}`;
|
|
134
|
+
const code = await this.generateInterfaceCode(syntheticalConfig, interfaceInfo, categoryUID);
|
|
135
|
+
return {
|
|
136
|
+
categoryUID,
|
|
137
|
+
outputFilePath,
|
|
138
|
+
weights: [
|
|
139
|
+
serverIndex,
|
|
140
|
+
projectIndex,
|
|
141
|
+
categoryIndex,
|
|
142
|
+
categoryIndex2
|
|
143
|
+
],
|
|
144
|
+
code
|
|
145
|
+
};
|
|
146
|
+
}));
|
|
147
|
+
const groupedInterfaceCodes = groupBy(interfaceCodes, (item) => item.outputFilePath);
|
|
148
|
+
return Object.keys(groupedInterfaceCodes).map((outputFilePath) => {
|
|
149
|
+
const categoryCode = [...uniq(sortByWeights(groupedInterfaceCodes[outputFilePath]).map((item) => item.categoryUID)).map((categoryUID) => {
|
|
150
|
+
if (syntheticalConfig.typesOnly) return "";
|
|
151
|
+
let text = "";
|
|
152
|
+
if (syntheticalConfig.withoutUrl !== true) text += `const devUrl${categoryUID} = ${JSON.stringify(syntheticalConfig.devUrl)} as any;
|
|
153
|
+
const mockUrl${categoryUID} = ${JSON.stringify(syntheticalConfig.mockUrl)} as any;
|
|
154
|
+
const prodUrl${categoryUID} = ${JSON.stringify(syntheticalConfig.prodUrl)} as any;`;
|
|
155
|
+
if (syntheticalConfig.ignoreUselessConfigVar !== true) text += `const dataKey${categoryUID} = ${JSON.stringify(syntheticalConfig.dataKey)} as any;`;
|
|
156
|
+
return dedent(text);
|
|
157
|
+
}), ...sortByWeights(groupedInterfaceCodes[outputFilePath]).map((item) => item.code)].filter(Boolean).join("\n\n");
|
|
158
|
+
if (!outputFileList[outputFilePath]) outputFileList[outputFilePath] = {
|
|
159
|
+
syntheticalConfig,
|
|
160
|
+
content: [],
|
|
161
|
+
requestFunctionFilePath: syntheticalConfig.requestFunctionFilePath ? path.resolve(this.options.cwd, syntheticalConfig.requestFunctionFilePath) : path.join(path.dirname(outputFilePath), "request.ts"),
|
|
162
|
+
requestHookMakerFilePath: syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled ? syntheticalConfig.reactHooks.requestHookMakerFilePath ? path.resolve(this.options.cwd, syntheticalConfig.reactHooks.requestHookMakerFilePath) : path.join(path.dirname(outputFilePath), "makeRequestHook.ts") : ""
|
|
163
|
+
};
|
|
164
|
+
return {
|
|
165
|
+
outputFilePath,
|
|
166
|
+
code: categoryCode,
|
|
167
|
+
weights: last(sortByWeights(groupedInterfaceCodes[outputFilePath])).weights
|
|
168
|
+
};
|
|
169
|
+
});
|
|
170
|
+
}))).flat();
|
|
171
|
+
for (const groupedCodes of values(groupBy(codes, (item) => item.outputFilePath))) {
|
|
172
|
+
sortByWeights(groupedCodes);
|
|
173
|
+
outputFileList[groupedCodes[0].outputFilePath].content.push(...groupedCodes.map((item) => item.code));
|
|
174
|
+
}
|
|
175
|
+
}));
|
|
176
|
+
}));
|
|
177
|
+
}));
|
|
178
|
+
return outputFileList;
|
|
179
|
+
}
|
|
180
|
+
async write(outputFileList) {
|
|
181
|
+
await Promise.all(Object.keys(outputFileList).map(async (outputFilePath) => {
|
|
182
|
+
let { content, requestFunctionFilePath, requestHookMakerFilePath, syntheticalConfig } = outputFileList[outputFilePath];
|
|
183
|
+
const rawRequestFunctionFilePath = requestFunctionFilePath;
|
|
184
|
+
const rawRequestHookMakerFilePath = requestHookMakerFilePath;
|
|
185
|
+
outputFilePath = outputFilePath.replace(/\.js(x)?$/, ".ts$1");
|
|
186
|
+
requestFunctionFilePath = requestFunctionFilePath.replace(/\.js(x)?$/, ".ts$1");
|
|
187
|
+
requestHookMakerFilePath = requestHookMakerFilePath.replace(/\.js(x)?$/, ".ts$1");
|
|
188
|
+
if (!syntheticalConfig.typesOnly) {
|
|
189
|
+
if (!await fs.pathExists(rawRequestFunctionFilePath)) await fs.outputFile(requestFunctionFilePath, dedent`
|
|
190
|
+
import type { RequestFunctionParams } from 'yapi-apifox-to-typescript'
|
|
191
|
+
|
|
192
|
+
export interface RequestOptions {
|
|
193
|
+
/**
|
|
194
|
+
* 使用的服务器。
|
|
195
|
+
*
|
|
196
|
+
* - \`prod\`: 生产服务器
|
|
197
|
+
* - \`dev\`: 测试服务器
|
|
198
|
+
* - \`mock\`: 模拟服务器
|
|
199
|
+
*
|
|
200
|
+
* @default prod
|
|
201
|
+
*/
|
|
202
|
+
server?: 'prod' | 'dev' | 'mock',
|
|
829
203
|
}
|
|
830
|
-
}));
|
|
831
|
-
|
|
832
|
-
case 7:
|
|
833
|
-
case "end":
|
|
834
|
-
return _context16.stop();
|
|
835
|
-
}
|
|
836
|
-
}
|
|
837
|
-
}, _callee16, this);
|
|
838
|
-
}));
|
|
839
|
-
|
|
840
|
-
function fetchProjectInfo(_x19) {
|
|
841
|
-
return _fetchProjectInfo.apply(this, arguments);
|
|
842
|
-
}
|
|
843
|
-
|
|
844
|
-
return fetchProjectInfo;
|
|
845
|
-
}()
|
|
846
|
-
/** 生成接口代码 */
|
|
847
|
-
;
|
|
848
|
-
|
|
849
|
-
_proto.generateInterfaceCode =
|
|
850
|
-
/*#__PURE__*/
|
|
851
|
-
function () {
|
|
852
|
-
var _generateInterfaceCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee17(syntheticalConfig, interfaceInfo, categoryUID) {
|
|
853
|
-
var _syntheticalConfig$js, _syntheticalConfig$js2, _syntheticalConfig$js3, _syntheticalConfig$js4;
|
|
854
|
-
|
|
855
|
-
var extendedInterfaceInfo, requestFunctionName, requestConfigName, requestConfigTypeName, requestDataTypeName, responseDataTypeName, requestDataJsonSchema, requestDataType, responseDataJsonSchema, responseDataType, isRequestDataOptional, requestHookName, paramNames, paramNamesLiteral, queryNames, queryNamesLiteral, genComment, requestFunctionExtraInfo, requestHeaders;
|
|
856
|
-
return _regeneratorRuntime.wrap(function _callee17$(_context17) {
|
|
857
|
-
while (1) {
|
|
858
|
-
switch (_context17.prev = _context17.next) {
|
|
859
|
-
case 0:
|
|
860
|
-
extendedInterfaceInfo = _extends({}, interfaceInfo, {
|
|
861
|
-
parsedPath: path.parse(interfaceInfo.path)
|
|
862
|
-
});
|
|
863
|
-
|
|
864
|
-
if (!isFunction(syntheticalConfig.getRequestFunctionName)) {
|
|
865
|
-
_context17.next = 7;
|
|
866
|
-
break;
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
_context17.next = 4;
|
|
870
|
-
return syntheticalConfig.getRequestFunctionName(extendedInterfaceInfo, changeCase);
|
|
871
|
-
|
|
872
|
-
case 4:
|
|
873
|
-
_context17.t0 = _context17.sent;
|
|
874
|
-
_context17.next = 8;
|
|
875
|
-
break;
|
|
876
204
|
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
_context17.next = 18;
|
|
896
|
-
break;
|
|
897
|
-
|
|
898
|
-
case 17:
|
|
899
|
-
_context17.t1 = changeCase.pascalCase(requestFunctionName + "Request");
|
|
900
|
-
|
|
901
|
-
case 18:
|
|
902
|
-
requestDataTypeName = _context17.t1;
|
|
903
|
-
|
|
904
|
-
if (!isFunction(syntheticalConfig.getResponseDataTypeName)) {
|
|
905
|
-
_context17.next = 25;
|
|
906
|
-
break;
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
_context17.next = 22;
|
|
910
|
-
return syntheticalConfig.getResponseDataTypeName(extendedInterfaceInfo, changeCase);
|
|
911
|
-
|
|
912
|
-
case 22:
|
|
913
|
-
_context17.t2 = _context17.sent;
|
|
914
|
-
_context17.next = 26;
|
|
915
|
-
break;
|
|
916
|
-
|
|
917
|
-
case 25:
|
|
918
|
-
_context17.t2 = changeCase.pascalCase(requestFunctionName + "Response");
|
|
919
|
-
|
|
920
|
-
case 26:
|
|
921
|
-
responseDataTypeName = _context17.t2;
|
|
922
|
-
requestDataJsonSchema = getRequestDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {});
|
|
923
|
-
_context17.next = 30;
|
|
924
|
-
return jsonSchemaToType(requestDataJsonSchema, requestDataTypeName);
|
|
925
|
-
|
|
926
|
-
case 30:
|
|
927
|
-
requestDataType = _context17.sent;
|
|
928
|
-
responseDataJsonSchema = getResponseDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {}, syntheticalConfig.dataKey);
|
|
929
|
-
_context17.next = 34;
|
|
930
|
-
return jsonSchemaToType(responseDataJsonSchema, responseDataTypeName);
|
|
931
|
-
|
|
932
|
-
case 34:
|
|
933
|
-
responseDataType = _context17.sent;
|
|
934
|
-
// @ts-ignore
|
|
935
|
-
isRequestDataOptional = /(\{\}|any)$/.test(requestDataType);
|
|
936
|
-
|
|
937
|
-
if (!(syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled)) {
|
|
938
|
-
_context17.next = 47;
|
|
939
|
-
break;
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
if (!isFunction(syntheticalConfig.reactHooks.getRequestHookName)) {
|
|
943
|
-
_context17.next = 43;
|
|
944
|
-
break;
|
|
945
|
-
}
|
|
946
|
-
|
|
947
|
-
_context17.next = 40;
|
|
948
|
-
return syntheticalConfig.reactHooks.getRequestHookName(extendedInterfaceInfo, changeCase);
|
|
949
|
-
|
|
950
|
-
case 40:
|
|
951
|
-
_context17.t4 = _context17.sent;
|
|
952
|
-
_context17.next = 44;
|
|
953
|
-
break;
|
|
954
|
-
|
|
955
|
-
case 43:
|
|
956
|
-
_context17.t4 = "use" + changeCase.pascalCase(requestFunctionName);
|
|
957
|
-
|
|
958
|
-
case 44:
|
|
959
|
-
_context17.t3 = _context17.t4;
|
|
960
|
-
_context17.next = 48;
|
|
961
|
-
break;
|
|
962
|
-
|
|
963
|
-
case 47:
|
|
964
|
-
_context17.t3 = '';
|
|
965
|
-
|
|
966
|
-
case 48:
|
|
967
|
-
requestHookName = _context17.t3;
|
|
968
|
-
// 支持路径参数
|
|
969
|
-
paramNames = (extendedInterfaceInfo.req_params
|
|
970
|
-
/* istanbul ignore next */
|
|
971
|
-
|| []).map(function (item) {
|
|
972
|
-
return item.name;
|
|
973
|
-
});
|
|
974
|
-
paramNamesLiteral = JSON.stringify(paramNames); // const paramNameType =
|
|
975
|
-
// paramNames.length === 0 ? 'string' : `'${paramNames.join("' | '")}'`
|
|
976
|
-
// 支持查询参数
|
|
977
|
-
|
|
978
|
-
queryNames = (extendedInterfaceInfo.req_query
|
|
979
|
-
/* istanbul ignore next */
|
|
980
|
-
|| []).map(function (item) {
|
|
981
|
-
return item.name;
|
|
982
|
-
});
|
|
983
|
-
queryNamesLiteral = JSON.stringify(queryNames); // const queryNameType =
|
|
984
|
-
// queryNames.length === 0 ? 'string' : `'${queryNames.join("' | '")}'`
|
|
985
|
-
// 接口注释
|
|
986
|
-
|
|
987
|
-
genComment = function genComment(genTitle) {
|
|
988
|
-
var _ref15 = _extends({}, syntheticalConfig.comment, syntheticalConfig.serverType === 'swagger' ? {
|
|
989
|
-
tag: false,
|
|
990
|
-
updateTime: false,
|
|
991
|
-
link: false
|
|
992
|
-
} : {}),
|
|
993
|
-
_ref15$enabled = _ref15.enabled,
|
|
994
|
-
isEnabled = _ref15$enabled === void 0 ? true : _ref15$enabled,
|
|
995
|
-
_ref15$title = _ref15.title,
|
|
996
|
-
hasTitle = _ref15$title === void 0 ? true : _ref15$title,
|
|
997
|
-
_ref15$category = _ref15.category,
|
|
998
|
-
hasCategory = _ref15$category === void 0 ? true : _ref15$category,
|
|
999
|
-
_ref15$tag = _ref15.tag,
|
|
1000
|
-
hasTag = _ref15$tag === void 0 ? true : _ref15$tag,
|
|
1001
|
-
_ref15$requestHeader = _ref15.requestHeader,
|
|
1002
|
-
hasRequestHeader = _ref15$requestHeader === void 0 ? true : _ref15$requestHeader,
|
|
1003
|
-
_ref15$updateTime = _ref15.updateTime,
|
|
1004
|
-
hasUpdateTime = _ref15$updateTime === void 0 ? true : _ref15$updateTime,
|
|
1005
|
-
_ref15$link = _ref15.link,
|
|
1006
|
-
hasLink = _ref15$link === void 0 ? true : _ref15$link,
|
|
1007
|
-
extraTags = _ref15.extraTags;
|
|
1008
|
-
|
|
1009
|
-
if (!isEnabled) {
|
|
1010
|
-
return '';
|
|
1011
|
-
} // 转义标题中的 /
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
var escapedTitle = String(extendedInterfaceInfo.title).replace(/\//g, '\\/');
|
|
1015
|
-
var description = hasLink ? "[" + escapedTitle + "\u2197](" + extendedInterfaceInfo._url + ")" : escapedTitle;
|
|
1016
|
-
var summary = [hasCategory && {
|
|
1017
|
-
label: '分类',
|
|
1018
|
-
value: hasLink ? "[" + extendedInterfaceInfo._category.name + "\u2197](" + extendedInterfaceInfo._category._url + ")" : extendedInterfaceInfo._category.name
|
|
1019
|
-
}, hasTag && {
|
|
1020
|
-
label: '标签',
|
|
1021
|
-
value: extendedInterfaceInfo.tag.map(function (tag) {
|
|
1022
|
-
return "`" + tag + "`";
|
|
205
|
+
export default function request<TResponseData>(
|
|
206
|
+
payload: RequestFunctionParams,
|
|
207
|
+
options: RequestOptions = {
|
|
208
|
+
server: 'prod',
|
|
209
|
+
},
|
|
210
|
+
): Promise<TResponseData> {
|
|
211
|
+
return new Promise<TResponseData>((resolve, reject) => {
|
|
212
|
+
// 基本地址
|
|
213
|
+
${syntheticalConfig.withoutUrl ? `const baseUrl = ''` : ` const baseUrl = options.server === 'mock'
|
|
214
|
+
? payload.mockUrl
|
|
215
|
+
: options.server === 'dev'
|
|
216
|
+
? payload.devUrl
|
|
217
|
+
: payload.prodUrl`}
|
|
218
|
+
|
|
219
|
+
// 请求地址
|
|
220
|
+
const url = \`\${baseUrl}\${payload.path}\`
|
|
221
|
+
|
|
222
|
+
// 具体请求逻辑
|
|
1023
223
|
})
|
|
1024
|
-
}
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
224
|
+
}
|
|
225
|
+
`);
|
|
226
|
+
if (syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled && !await fs.pathExists(rawRequestHookMakerFilePath)) await fs.outputFile(requestHookMakerFilePath, dedent`
|
|
227
|
+
import { useState, useEffect } from 'react'
|
|
228
|
+
import type { RequestConfig } from 'yapi-apifox-to-typescript'
|
|
229
|
+
import type { Request } from ${JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, outputFilePath))}
|
|
230
|
+
import baseRequest from ${JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, requestFunctionFilePath))}
|
|
231
|
+
|
|
232
|
+
export default function makeRequestHook<TRequestData, TRequestConfig extends RequestConfig, TRequestResult extends ReturnType<typeof baseRequest>>(request: Request<TRequestData, TRequestConfig, TRequestResult>) {
|
|
233
|
+
type Data = TRequestResult extends Promise<infer R> ? R : TRequestResult
|
|
234
|
+
return function useRequest(requestData: TRequestData) {
|
|
235
|
+
// 一个简单的 Hook 实现,实际项目可结合其他库使用,比如:
|
|
236
|
+
// @umijs/hooks 的 useRequest (https://github.com/umijs/hooks)
|
|
237
|
+
// swr (https://github.com/zeit/swr)
|
|
238
|
+
|
|
239
|
+
const [loading, setLoading] = useState(true)
|
|
240
|
+
const [data, setData] = useState<Data>()
|
|
241
|
+
|
|
242
|
+
useEffect(() => {
|
|
243
|
+
request(requestData).then(data => {
|
|
244
|
+
setLoading(false)
|
|
245
|
+
setData(data as any)
|
|
246
|
+
})
|
|
247
|
+
}, [JSON.stringify(requestData)])
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
loading,
|
|
251
|
+
data,
|
|
252
|
+
}
|
|
1045
253
|
}
|
|
1046
254
|
}
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
return _context17.abrupt("return", dedent(_templateObject10 || (_templateObject10 = _taggedTemplateLiteralLoose(["\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n "])), genComment(function (title) {
|
|
1084
|
-
return "\u63A5\u53E3 " + title + " \u7684 **\u8BF7\u6C42\u7C7B\u578B**";
|
|
1085
|
-
}), requestDataType.trim(), genComment(function (title) {
|
|
1086
|
-
return "\u63A5\u53E3 " + title + " \u7684 **\u8FD4\u56DE\u7C7B\u578B**";
|
|
1087
|
-
}), responseDataType.trim(), syntheticalConfig.typesOnly ? '' : dedent(_templateObject11 || (_templateObject11 = _taggedTemplateLiteralLoose(["\n ", "\n ", "\n path: ", ",\n method: Method.", ",\n ", "", "", "", "requestBodyType: RequestBodyType.", ",\n ", "\n }\n\n ", "\n export const ", " = ", " (\n requestData", ": ", ",\n ...args: UserRequestRestArgs\n ) => {\n return request<", ">(\n prepare(", ", requestData),\n ...args,\n )\n }\n\n ", ".requestConfig = ", "\n\n ", "\n "])), genComment(function (title) {
|
|
1088
|
-
return "\u63A5\u53E3 " + title + " \u7684 **\u8BF7\u6C42\u914D\u7F6E**";
|
|
1089
|
-
}), syntheticalConfig.withoutUrl !== true ? "const " + requestConfigName + ": " + requestConfigTypeName + " = " + COMPRESSOR_TREE_SHAKING_ANNOTATION + " {\n mockUrl: mockUrl" + categoryUID + ",\n devUrl: devUrl" + categoryUID + ",\n prodUrl: prodUrl" + categoryUID + "," : "const " + requestConfigName + ": " + requestConfigTypeName + " = " + COMPRESSOR_TREE_SHAKING_ANNOTATION + " {", JSON.stringify(extendedInterfaceInfo.path), extendedInterfaceInfo.method, paramNames.length === 0 ? '' : "paramNames: " + paramNamesLiteral + ",", queryNames.length === 0 ? '' : "queryNames: " + queryNamesLiteral + ",", syntheticalConfig.queryStringArrayFormat ? "queryStringArrayFormat: QueryStringArrayFormat." + syntheticalConfig.queryStringArrayFormat + "," : '', requestHeaders === '{}' ? '' : "requestHeaders: " + requestHeaders + ",", extendedInterfaceInfo.method === Method.GET ? RequestBodyType.query : extendedInterfaceInfo.req_body_type
|
|
1090
|
-
/* istanbul ignore next */
|
|
1091
|
-
|| RequestBodyType.none, syntheticalConfig.ignoreUselessConfigVar ? "" : "responseBodyType: ResponseBodyType." + extendedInterfaceInfo.res_body_type + ",\n dataKey: dataKey" + categoryUID + ",\n requestDataOptional: " + JSON.stringify(isRequestDataOptional) + ",\n requestDataJsonSchema: " + JSON.stringify((_syntheticalConfig$js = syntheticalConfig.jsonSchema) != null && _syntheticalConfig$js.enabled && ((_syntheticalConfig$js2 = syntheticalConfig.jsonSchema) == null ? void 0 : _syntheticalConfig$js2.requestData) !== false ? requestDataJsonSchema : {}) + ",\n responseDataJsonSchema: " + JSON.stringify((_syntheticalConfig$js3 = syntheticalConfig.jsonSchema) != null && _syntheticalConfig$js3.enabled && ((_syntheticalConfig$js4 = syntheticalConfig.jsonSchema) == null ? void 0 : _syntheticalConfig$js4.responseData) !== false ? responseDataJsonSchema : {}) + ",\n requestFunctionName: " + JSON.stringify(requestFunctionName) + ",\n extraInfo: " + JSON.stringify(requestFunctionExtraInfo), genComment(function (title) {
|
|
1092
|
-
return "\u63A5\u53E3 " + title + " \u7684 **\u8BF7\u6C42\u51FD\u6570**";
|
|
1093
|
-
}), requestFunctionName, COMPRESSOR_TREE_SHAKING_ANNOTATION, isRequestDataOptional ? '?' : '', requestDataTypeName, responseDataTypeName, requestConfigName, requestFunctionName, requestConfigName, !syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? '' : dedent(_templateObject12 || (_templateObject12 = _taggedTemplateLiteralLoose(["\n ", "\n export const ", " = ", " makeRequestHook<", ", ", ", ReturnType<typeof ", ">>(", ")\n "])), genComment(function (title) {
|
|
1094
|
-
return "\u63A5\u53E3 " + title + " \u7684 **React Hook**";
|
|
1095
|
-
}), requestHookName, COMPRESSOR_TREE_SHAKING_ANNOTATION, requestDataTypeName, requestConfigTypeName, requestFunctionName, requestFunctionName))));
|
|
1096
|
-
|
|
1097
|
-
case 64:
|
|
1098
|
-
case "end":
|
|
1099
|
-
return _context17.stop();
|
|
1100
|
-
}
|
|
1101
|
-
}
|
|
1102
|
-
}, _callee17);
|
|
1103
|
-
}));
|
|
1104
|
-
|
|
1105
|
-
function generateInterfaceCode(_x20, _x21, _x22) {
|
|
1106
|
-
return _generateInterfaceCode.apply(this, arguments);
|
|
1107
|
-
}
|
|
1108
|
-
|
|
1109
|
-
return generateInterfaceCode;
|
|
1110
|
-
}();
|
|
1111
|
-
|
|
1112
|
-
_proto.destroy = /*#__PURE__*/function () {
|
|
1113
|
-
var _destroy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee19() {
|
|
1114
|
-
return _regeneratorRuntime.wrap(function _callee19$(_context19) {
|
|
1115
|
-
while (1) {
|
|
1116
|
-
switch (_context19.prev = _context19.next) {
|
|
1117
|
-
case 0:
|
|
1118
|
-
return _context19.abrupt("return", Promise.all(this.disposes.map( /*#__PURE__*/function () {
|
|
1119
|
-
var _ref16 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(dispose) {
|
|
1120
|
-
return _regeneratorRuntime.wrap(function _callee18$(_context18) {
|
|
1121
|
-
while (1) {
|
|
1122
|
-
switch (_context18.prev = _context18.next) {
|
|
1123
|
-
case 0:
|
|
1124
|
-
return _context18.abrupt("return", dispose());
|
|
1125
|
-
|
|
1126
|
-
case 1:
|
|
1127
|
-
case "end":
|
|
1128
|
-
return _context18.stop();
|
|
255
|
+
`);
|
|
256
|
+
}
|
|
257
|
+
const rawOutputContent = dedent`
|
|
258
|
+
/* tslint:disable */
|
|
259
|
+
/* eslint-disable */
|
|
260
|
+
|
|
261
|
+
/* 该文件由 yapi-apifox-to-typescript 自动生成,请勿直接修改!!! */
|
|
262
|
+
|
|
263
|
+
${syntheticalConfig.typesOnly ? dedent`
|
|
264
|
+
// @ts-ignore
|
|
265
|
+
type FileData = File
|
|
266
|
+
|
|
267
|
+
${content.join("\n\n").trim()}
|
|
268
|
+
` : dedent`
|
|
269
|
+
// @ts-ignore
|
|
270
|
+
// prettier-ignore
|
|
271
|
+
import { QueryStringArrayFormat, Method, RequestBodyType, ${syntheticalConfig.ignoreUselessConfigVar ? `` : `ResponseBodyType, `}FileData, prepare } from 'yapi-apifox-to-typescript'
|
|
272
|
+
// @ts-ignore
|
|
273
|
+
// prettier-ignore
|
|
274
|
+
import type { RequestConfig, RequestFunctionRestArgs } from 'yapi-apifox-to-typescript'
|
|
275
|
+
// @ts-ignore
|
|
276
|
+
import request from ${JSON.stringify(getNormalizedRelativePath(outputFilePath, requestFunctionFilePath))}
|
|
277
|
+
${!syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? "" : dedent`
|
|
278
|
+
// @ts-ignore
|
|
279
|
+
import makeRequestHook from ${JSON.stringify(getNormalizedRelativePath(outputFilePath, requestHookMakerFilePath))}
|
|
280
|
+
`}
|
|
281
|
+
|
|
282
|
+
type UserRequestRestArgs = RequestFunctionRestArgs<typeof request>
|
|
283
|
+
${!syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? "" : `\n${dedent`
|
|
284
|
+
// Request: 目前 React Hooks 功能有用到
|
|
285
|
+
export type Request<TRequestData, TRequestConfig extends RequestConfig, TRequestResult> = (
|
|
286
|
+
TRequestConfig['requestDataOptional'] extends true
|
|
287
|
+
? (requestData?: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult
|
|
288
|
+
: (requestData: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult
|
|
289
|
+
) & {
|
|
290
|
+
requestConfig: TRequestConfig
|
|
1129
291
|
}
|
|
1130
|
-
}
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
}
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
292
|
+
`}`}
|
|
293
|
+
|
|
294
|
+
${content.join("\n\n").trim()}
|
|
295
|
+
`}
|
|
296
|
+
`;
|
|
297
|
+
const prettyOutputContent = await (await getPrettier(this.options.cwd)).format(rawOutputContent, {
|
|
298
|
+
...await getCachedPrettierOptions(),
|
|
299
|
+
filepath: outputFilePath
|
|
300
|
+
});
|
|
301
|
+
const outputContent = `${dedent`
|
|
302
|
+
/* prettier-ignore-start */
|
|
303
|
+
${prettyOutputContent}
|
|
304
|
+
/* prettier-ignore-end */
|
|
305
|
+
`}\n`;
|
|
306
|
+
await fs.outputFile(outputFilePath, outputContent);
|
|
307
|
+
if (syntheticalConfig.target === "javascript") {
|
|
308
|
+
await this.tsc(outputFilePath);
|
|
309
|
+
await Promise.all([
|
|
310
|
+
fs.remove(requestFunctionFilePath).catch(noop),
|
|
311
|
+
fs.remove(requestHookMakerFilePath).catch(noop),
|
|
312
|
+
fs.remove(outputFilePath).catch(noop)
|
|
313
|
+
]);
|
|
314
|
+
}
|
|
315
|
+
}));
|
|
316
|
+
if (this.barrelOutputMap.size > 0) {
|
|
317
|
+
const prettier = await getPrettier(this.options.cwd);
|
|
318
|
+
const barrelPaths = Array.from(this.barrelOutputMap.keys());
|
|
319
|
+
for (let bi = 0; bi < barrelPaths.length; bi++) {
|
|
320
|
+
const barrelPath = barrelPaths[bi];
|
|
321
|
+
const modulesDir = path.join(path.dirname(barrelPath), "modules");
|
|
322
|
+
const moduleExports = Object.keys(outputFileList).filter((f) => f.startsWith(modulesDir)).map((f) => `./modules/${path.basename(f, path.extname(f))}`).sort();
|
|
323
|
+
if (moduleExports.length === 0) continue;
|
|
324
|
+
const rawBarrelContent = dedent`
|
|
325
|
+
/* tslint:disable */
|
|
326
|
+
/* eslint-disable */
|
|
327
|
+
|
|
328
|
+
/* 该文件由 yapi-apifox-to-typescript 自动生成,请勿直接修改!!! */
|
|
329
|
+
|
|
330
|
+
${moduleExports.map((m) => `export * from ${JSON.stringify(m)}`).join("\n")}
|
|
331
|
+
`;
|
|
332
|
+
const prettyBarrelContent = await prettier.format(rawBarrelContent, {
|
|
333
|
+
...await getCachedPrettierOptions(),
|
|
334
|
+
filepath: barrelPath
|
|
335
|
+
});
|
|
336
|
+
await fs.outputFile(barrelPath, `${dedent`
|
|
337
|
+
/* prettier-ignore-start */
|
|
338
|
+
${prettyBarrelContent}
|
|
339
|
+
/* prettier-ignore-end */
|
|
340
|
+
`}\n`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
async tsc(file) {
|
|
345
|
+
return new Promise((resolve) => {
|
|
346
|
+
const command = `${__require("os").platform() === "win32" ? "node " : ""}${JSON.stringify(__require.resolve(`typescript/bin/tsc`))}`;
|
|
347
|
+
exec(`${command} --target ES2019 --module ESNext --jsx preserve --declaration --esModuleInterop ${JSON.stringify(file)}`, {
|
|
348
|
+
cwd: this.options.cwd,
|
|
349
|
+
env: process.env
|
|
350
|
+
}, () => resolve());
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
async fetchApi(url, query) {
|
|
354
|
+
const res = await httpGet(url, query);
|
|
355
|
+
/* istanbul ignore next */
|
|
356
|
+
if (res && res.errcode) throwError(`${res.errmsg} [请求地址: ${url}] [请求参数: ${new URLSearchParams(query).toString()}]`);
|
|
357
|
+
return res.data || res;
|
|
358
|
+
}
|
|
359
|
+
/** 获取分类的接口列表 */
|
|
360
|
+
async fetchInterfaceList({ serverUrl, token, id }) {
|
|
361
|
+
const category = (await this.fetchExport({
|
|
362
|
+
serverUrl,
|
|
363
|
+
token
|
|
364
|
+
}) || []).find((cat) => !isEmpty(cat) && !isEmpty(cat.list) && cat.list[0].catid === id);
|
|
365
|
+
if (category) category.list.forEach((interfaceInfo) => {
|
|
366
|
+
interfaceInfo._category = omit(category, ["list"]);
|
|
367
|
+
});
|
|
368
|
+
return category ? category.list : [];
|
|
369
|
+
}
|
|
370
|
+
/** 获取项目信息 */
|
|
371
|
+
async fetchProjectInfo(syntheticalConfig) {
|
|
372
|
+
const projectInfo = await this.fetchProject(syntheticalConfig);
|
|
373
|
+
const projectCats = await this.fetchApi(`${syntheticalConfig.serverUrl}/api/interface/getCatMenu`, {
|
|
374
|
+
token: syntheticalConfig.token,
|
|
375
|
+
project_id: projectInfo._id
|
|
376
|
+
});
|
|
377
|
+
return {
|
|
378
|
+
...projectInfo,
|
|
379
|
+
cats: projectCats,
|
|
380
|
+
getMockUrl: () => `${syntheticalConfig.serverUrl}/mock/${projectInfo._id}`,
|
|
381
|
+
getDevUrl: (devEnvName) => {
|
|
382
|
+
const env = projectInfo.env.find((e) => e.name === devEnvName);
|
|
383
|
+
return env && env.domain || "";
|
|
384
|
+
},
|
|
385
|
+
getProdUrl: (prodEnvName) => {
|
|
386
|
+
const env = projectInfo.env.find((e) => e.name === prodEnvName);
|
|
387
|
+
return env && env.domain || "";
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
/** 生成接口代码 */
|
|
392
|
+
async generateInterfaceCode(syntheticalConfig, interfaceInfo, categoryUID) {
|
|
393
|
+
const extendedInterfaceInfo = {
|
|
394
|
+
...interfaceInfo,
|
|
395
|
+
parsedPath: path.parse(interfaceInfo.path)
|
|
396
|
+
};
|
|
397
|
+
const requestFunctionName = isFunction(syntheticalConfig.getRequestFunctionName) ? await syntheticalConfig.getRequestFunctionName(extendedInterfaceInfo, changeCase) : changeCase.camelCase(extendedInterfaceInfo.parsedPath.name);
|
|
398
|
+
const requestConfigName = changeCase.camelCase(`${requestFunctionName}RequestConfig`);
|
|
399
|
+
const requestConfigTypeName = "RequestConfig";
|
|
400
|
+
const requestDataTypeName = isFunction(syntheticalConfig.getRequestDataTypeName) ? await syntheticalConfig.getRequestDataTypeName(extendedInterfaceInfo, changeCase) : changeCase.pascalCase(`${requestFunctionName}Request`);
|
|
401
|
+
const responseDataTypeName = isFunction(syntheticalConfig.getResponseDataTypeName) ? await syntheticalConfig.getResponseDataTypeName(extendedInterfaceInfo, changeCase) : changeCase.pascalCase(`${requestFunctionName}Response`);
|
|
402
|
+
const requestDataJsonSchema = getRequestDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {});
|
|
403
|
+
const requestDataType = await jsonSchemaToType(requestDataJsonSchema, requestDataTypeName);
|
|
404
|
+
const responseDataJsonSchema = getResponseDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {}, syntheticalConfig.dataKey);
|
|
405
|
+
const responseDataType = await jsonSchemaToType(responseDataJsonSchema, responseDataTypeName);
|
|
406
|
+
const isRequestDataOptional = /(\{\}|any)$/s.test(requestDataType);
|
|
407
|
+
const requestHookName = syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled ? isFunction(syntheticalConfig.reactHooks.getRequestHookName) ? await syntheticalConfig.reactHooks.getRequestHookName(extendedInterfaceInfo, changeCase) : `use${changeCase.pascalCase(requestFunctionName)}` : "";
|
|
408
|
+
const paramNames = (extendedInterfaceInfo.req_params || []).map((item) => item.name);
|
|
409
|
+
const paramNamesLiteral = JSON.stringify(paramNames);
|
|
410
|
+
const queryNames = (extendedInterfaceInfo.req_query || []).map((item) => item.name);
|
|
411
|
+
const queryNamesLiteral = JSON.stringify(queryNames);
|
|
412
|
+
const genComment = (genTitle) => {
|
|
413
|
+
const { enabled: isEnabled = true, title: hasTitle = true, category: hasCategory = true, tag: hasTag = true, requestHeader: hasRequestHeader = true, updateTime: hasUpdateTime = true, link: hasLink = true, extraTags } = {
|
|
414
|
+
...syntheticalConfig.comment,
|
|
415
|
+
...syntheticalConfig.serverType === "swagger" || syntheticalConfig.serverType === "local" ? {
|
|
416
|
+
tag: false,
|
|
417
|
+
updateTime: false,
|
|
418
|
+
link: false
|
|
419
|
+
} : {}
|
|
420
|
+
};
|
|
421
|
+
if (!isEnabled) return "";
|
|
422
|
+
const escapedTitle = String(extendedInterfaceInfo.title).replace(/\//g, "\\/");
|
|
423
|
+
const description = hasLink ? `[${escapedTitle}↗](${extendedInterfaceInfo._url})` : escapedTitle;
|
|
424
|
+
const summary = [
|
|
425
|
+
hasCategory && {
|
|
426
|
+
label: "分类",
|
|
427
|
+
value: hasLink ? `[${extendedInterfaceInfo._category.name}↗](${extendedInterfaceInfo._category._url})` : extendedInterfaceInfo._category.name
|
|
428
|
+
},
|
|
429
|
+
hasTag && {
|
|
430
|
+
label: "标签",
|
|
431
|
+
value: extendedInterfaceInfo.tag.map((tag) => `\`${tag}\``)
|
|
432
|
+
},
|
|
433
|
+
hasRequestHeader && {
|
|
434
|
+
label: "请求头",
|
|
435
|
+
value: `\`${extendedInterfaceInfo.method.toUpperCase()} ${extendedInterfaceInfo.path}\``
|
|
436
|
+
},
|
|
437
|
+
hasUpdateTime && {
|
|
438
|
+
label: "更新时间",
|
|
439
|
+
value: process.env.JEST_WORKER_ID ? String(extendedInterfaceInfo.up_time) : `\`${dayjs(extendedInterfaceInfo.up_time * 1e3).format("YYYY-MM-DD HH:mm:ss")}\``
|
|
440
|
+
}
|
|
441
|
+
];
|
|
442
|
+
if (typeof extraTags === "function") {
|
|
443
|
+
const tags = extraTags(extendedInterfaceInfo);
|
|
444
|
+
for (const tag of tags) (tag.position === "start" ? summary.unshift : summary.push).call(summary, {
|
|
445
|
+
label: tag.name,
|
|
446
|
+
value: tag.value
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
const titleComment = hasTitle ? dedent`
|
|
450
|
+
* ${genTitle(description)}
|
|
451
|
+
*
|
|
452
|
+
` : "";
|
|
453
|
+
const extraComment = summary.filter((item) => typeof item !== "boolean" && !isEmpty(item.value)).map((item) => {
|
|
454
|
+
const _item = item;
|
|
455
|
+
return `* @${_item.label} ${castArray(_item.value).join(", ")}`;
|
|
456
|
+
}).join("\n");
|
|
457
|
+
return dedent`
|
|
458
|
+
/**
|
|
459
|
+
${[titleComment, extraComment].filter(Boolean).join("\n")}
|
|
460
|
+
*/
|
|
461
|
+
`;
|
|
462
|
+
};
|
|
463
|
+
const requestFunctionExtraInfo = typeof syntheticalConfig.setRequestFunctionExtraInfo === "function" ? await syntheticalConfig.setRequestFunctionExtraInfo(extendedInterfaceInfo, changeCase) : {};
|
|
464
|
+
const requestHeaders = JSON.stringify((extendedInterfaceInfo.req_headers || []).filter((item) => item.name.toLowerCase() !== "content-type").reduce((res, item) => {
|
|
465
|
+
res[item.name] = item.value;
|
|
466
|
+
return res;
|
|
467
|
+
}, {}));
|
|
468
|
+
return dedent`
|
|
469
|
+
${genComment((title) => `接口 ${title} 的 **请求类型**`)}
|
|
470
|
+
${requestDataType.trim()}
|
|
471
|
+
|
|
472
|
+
${genComment((title) => `接口 ${title} 的 **返回类型**`)}
|
|
473
|
+
${responseDataType.trim()}
|
|
474
|
+
|
|
475
|
+
${syntheticalConfig.typesOnly ? "" : dedent`
|
|
476
|
+
${genComment((title) => `接口 ${title} 的 **请求配置**`)}
|
|
477
|
+
${syntheticalConfig.withoutUrl !== true ? `const ${requestConfigName}: ${requestConfigTypeName} = ${COMPRESSOR_TREE_SHAKING_ANNOTATION} {
|
|
478
|
+
mockUrl: mockUrl${categoryUID},
|
|
479
|
+
devUrl: devUrl${categoryUID},
|
|
480
|
+
prodUrl: prodUrl${categoryUID},` : `const ${requestConfigName}: ${requestConfigTypeName} = ${COMPRESSOR_TREE_SHAKING_ANNOTATION} {`}
|
|
481
|
+
path: ${JSON.stringify(extendedInterfaceInfo.path)},
|
|
482
|
+
method: Method.${extendedInterfaceInfo.method},
|
|
483
|
+
${paramNames.length === 0 ? "" : `paramNames: ${paramNamesLiteral},`}${queryNames.length === 0 ? "" : `queryNames: ${queryNamesLiteral},`}${syntheticalConfig.queryStringArrayFormat ? `queryStringArrayFormat: QueryStringArrayFormat.${syntheticalConfig.queryStringArrayFormat},` : ""}${requestHeaders === "{}" ? "" : `requestHeaders: ${requestHeaders},`}requestBodyType: RequestBodyType.${extendedInterfaceInfo.method === Method.GET ? RequestBodyType.query : extendedInterfaceInfo.req_body_type || RequestBodyType.none},
|
|
484
|
+
${syntheticalConfig.ignoreUselessConfigVar ? `` : `responseBodyType: ResponseBodyType.${extendedInterfaceInfo.res_body_type},
|
|
485
|
+
dataKey: dataKey${categoryUID},
|
|
486
|
+
requestDataOptional: ${JSON.stringify(isRequestDataOptional)},
|
|
487
|
+
requestDataJsonSchema: ${JSON.stringify(syntheticalConfig.jsonSchema?.enabled && syntheticalConfig.jsonSchema?.requestData !== false ? requestDataJsonSchema : {})},
|
|
488
|
+
responseDataJsonSchema: ${JSON.stringify(syntheticalConfig.jsonSchema?.enabled && syntheticalConfig.jsonSchema?.responseData !== false ? responseDataJsonSchema : {})},
|
|
489
|
+
requestFunctionName: ${JSON.stringify(requestFunctionName)},
|
|
490
|
+
extraInfo: ${JSON.stringify(requestFunctionExtraInfo)}`}
|
|
491
|
+
}
|
|
1150
492
|
|
|
1151
|
-
|
|
1152
|
-
|
|
493
|
+
${genComment((title) => `接口 ${title} 的 **请求函数**`)}
|
|
494
|
+
export const ${requestFunctionName} = ${COMPRESSOR_TREE_SHAKING_ANNOTATION} (
|
|
495
|
+
requestData${isRequestDataOptional ? "?" : ""}: ${requestDataTypeName},
|
|
496
|
+
...args: UserRequestRestArgs
|
|
497
|
+
) => {
|
|
498
|
+
return request<${responseDataTypeName}>(
|
|
499
|
+
prepare(${requestConfigName}, requestData),
|
|
500
|
+
...args,
|
|
501
|
+
)
|
|
502
|
+
}
|
|
1153
503
|
|
|
1154
|
-
|
|
1155
|
-
|
|
504
|
+
${requestFunctionName}.requestConfig = ${requestConfigName}
|
|
505
|
+
|
|
506
|
+
${!syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? "" : dedent`
|
|
507
|
+
${genComment((title) => `接口 ${title} 的 **React Hook**`)}
|
|
508
|
+
export const ${requestHookName} = ${COMPRESSOR_TREE_SHAKING_ANNOTATION} makeRequestHook<${requestDataTypeName}, ${requestConfigTypeName}, ReturnType<typeof ${requestFunctionName}>>(${requestFunctionName})
|
|
509
|
+
`}
|
|
510
|
+
`}
|
|
511
|
+
`;
|
|
512
|
+
}
|
|
513
|
+
async destroy() {
|
|
514
|
+
return Promise.all(this.disposes.map(async (dispose) => dispose()));
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
//#endregion
|
|
518
|
+
export { Generator };
|