yapi-to-typescript
Version:
根据 YApi 的接口定义生成 TypeScript/JavaScript 的接口类型及其请求函数代码。
885 lines (746 loc) • 64 kB
JavaScript
import _createForOfIteratorHelperLoose from "@babel/runtime/helpers/esm/createForOfIteratorHelperLoose";
import _taggedTemplateLiteralLoose from "@babel/runtime/helpers/esm/taggedTemplateLiteralLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7, _templateObject8, _templateObject9, _templateObject10, _templateObject11, _templateObject12, _templateObject13;
import _regeneratorRuntime from "@babel/runtime/regenerator";
import * as changeCase from 'change-case';
import dayjs from 'dayjs';
import fs from 'fs-extra';
import path from 'path';
import { castArray, cloneDeepFast, dedent, groupBy, isEmpty, isFunction, last, memoize, noop, omit, uniq, values } from 'vtils';
import { Method, QueryStringArrayFormat, RequestBodyType } from './types';
import { exec } from 'child_process';
import { getCachedPrettierOptions, getNormalizedRelativePath, getPrettier, getRequestDataJsonSchema, getResponseDataJsonSchema, httpGet, jsonSchemaToType, sortByWeights, throwError } from './utils';
import { SwaggerToYApiServer } from './SwaggerToYApiServer';
/**
* @see https://webpack.js.org/guides/tree-shaking/#mark-a-function-call-as-side-effect-free
* @see https://terser.org/docs/api-reference.html#annotations
*/
var COMPRESSOR_TREE_SHAKING_ANNOTATION = '/*#__PURE__*/';
export var Generator = /*#__PURE__*/function () {
/** 配置 */
function Generator(config, options) {
var _this = this;
if (options === void 0) {
options = {
cwd: process.cwd()
};
}
this.options = options;
this.config = [];
this.disposes = [];
this.fetchProject = memoize( /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref) {
var serverUrl, token, projectInfo, basePath;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
serverUrl = _ref.serverUrl, token = _ref.token;
_context.next = 3;
return _this.fetchApi(serverUrl + "/api/project/get", {
token: token
});
case 3:
projectInfo = _context.sent;
basePath = ("/" + (projectInfo.basepath || '/')).replace(/\/+$/, '').replace(/^\/+/, '/');
projectInfo.basepath = basePath; // 实现项目在 YApi 上的地址
projectInfo._url = serverUrl + "/project/" + projectInfo._id + "/interface/api";
return _context.abrupt("return", projectInfo);
case 8:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x) {
return _ref2.apply(this, arguments);
};
}(), function (_ref3) {
var serverUrl = _ref3.serverUrl,
token = _ref3.token;
return serverUrl + "|" + token;
});
this.fetchExport = memoize( /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref4) {
var serverUrl, token, projectInfo, categoryList;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
serverUrl = _ref4.serverUrl, token = _ref4.token;
_context2.next = 3;
return _this.fetchProject({
serverUrl: serverUrl,
token: token
});
case 3:
projectInfo = _context2.sent;
_context2.next = 6;
return _this.fetchApi(serverUrl + "/api/plugin/export", {
type: 'json',
status: 'all',
isWiki: 'false',
token: token
});
case 6:
categoryList = _context2.sent;
return _context2.abrupt("return", categoryList.map(function (cat) {
var _cat$list, _cat$list$, _cat$list2, _cat$list2$;
var projectId = ((_cat$list = cat.list) == null ? void 0 : (_cat$list$ = _cat$list[0]) == null ? void 0 : _cat$list$.project_id) || 0;
var catId = ((_cat$list2 = cat.list) == null ? void 0 : (_cat$list2$ = _cat$list2[0]) == null ? void 0 : _cat$list2$.catid) || 0; // 实现分类在 YApi 上的地址
// 实现分类在 YApi 上的地址
cat._url = serverUrl + "/project/" + projectId + "/interface/api/cat_" + catId;
cat.list = (cat.list || []).map(function (item) {
var interfaceId = item._id; // 实现接口在 YApi 上的地址
// 实现接口在 YApi 上的地址
item._url = serverUrl + "/project/" + projectId + "/interface/api/" + interfaceId;
item.path = "" + projectInfo.basepath + item.path;
return item;
});
return cat;
}));
case 8:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function (_x2) {
return _ref5.apply(this, arguments);
};
}(), function (_ref6) {
var serverUrl = _ref6.serverUrl,
token = _ref6.token;
return serverUrl + "|" + token;
});
// config 可能是对象或数组,统一为数组
this.config = castArray(config);
}
var _proto = Generator.prototype;
_proto.prepare = /*#__PURE__*/function () {
var _prepare = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
var _this2 = this;
return _regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return Promise.all( // config 可能是对象或数组,统一为数组
this.config.map( /*#__PURE__*/function () {
var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(item) {
var swaggerToYApiServer;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!(item.serverType === 'swagger')) {
_context3.next = 6;
break;
}
swaggerToYApiServer = new SwaggerToYApiServer({
swaggerJsonUrl: item.serverUrl
});
_context3.next = 4;
return swaggerToYApiServer.start();
case 4:
item.serverUrl = _context3.sent;
_this2.disposes.push(function () {
return swaggerToYApiServer.stop();
});
case 6:
if (item.serverUrl) {
// 去除地址后面的 /
// fix: https://github.com/fjc0k/yapi-to-typescript/issues/22
item.serverUrl = item.serverUrl.replace(/\/+$/, '');
}
return _context3.abrupt("return", item);
case 8:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function (_x3) {
return _ref7.apply(this, arguments);
};
}()));
case 2:
this.config = _context4.sent;
case 3:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function prepare() {
return _prepare.apply(this, arguments);
}
return prepare;
}();
_proto.generate = /*#__PURE__*/function () {
var _generate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10() {
var _this3 = this;
var outputFileList;
return _regeneratorRuntime.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
outputFileList = Object.create(null);
_context10.next = 3;
return Promise.all(this.config.map( /*#__PURE__*/function () {
var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(serverConfig, serverIndex) {
var projects;
return _regeneratorRuntime.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
projects = serverConfig.projects.reduce(function (projects, project) {
projects.push.apply(projects, castArray(project.token).map(function (token) {
return _extends({}, project, {
token: token
});
}));
return projects;
}, []);
return _context9.abrupt("return", Promise.all(projects.map( /*#__PURE__*/function () {
var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(projectConfig, projectIndex) {
var projectInfo;
return _regeneratorRuntime.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
_context8.next = 2;
return _this3.fetchProjectInfo(_extends({}, serverConfig, projectConfig));
case 2:
projectInfo = _context8.sent;
_context8.next = 5;
return Promise.all(projectConfig.categories.map( /*#__PURE__*/function () {
var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(categoryConfig, categoryIndex) {
var categoryIds, _categoryIds, excludedCategoryIds, codes, _iterator, _step, _outputFileList$group, groupedCodes;
return _regeneratorRuntime.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
// 分类处理
// 数组化
categoryIds = castArray(categoryConfig.id); // 全部分类
// 全部分类
if (categoryIds.includes(0)) {
(_categoryIds = categoryIds).push.apply(_categoryIds, projectInfo.cats.map(function (cat) {
return cat._id;
}));
} // 唯一化
// 唯一化
categoryIds = uniq(categoryIds); // 去掉被排除的分类
// 去掉被排除的分类
excludedCategoryIds = categoryIds.filter(function (id) {
return id < 0;
}).map(Math.abs);
categoryIds = categoryIds.filter(function (id) {
return !excludedCategoryIds.includes(Math.abs(id));
}); // 删除不存在的分类
// 删除不存在的分类
categoryIds = categoryIds.filter(function (id) {
return !!projectInfo.cats.find(function (cat) {
return cat._id === id;
});
}); // 顺序化
// 顺序化
categoryIds = categoryIds.sort();
_context7.next = 9;
return Promise.all(categoryIds.map( /*#__PURE__*/function () {
var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(id, categoryIndex2) {
var syntheticalConfig, interfaceList, interfaceCodes, groupedInterfaceCodes;
return _regeneratorRuntime.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
categoryConfig = _extends({}, categoryConfig, {
id: id
});
syntheticalConfig = _extends({}, serverConfig, projectConfig, categoryConfig, {
mockUrl: projectInfo.getMockUrl()
});
syntheticalConfig.target = syntheticalConfig.target || 'typescript';
syntheticalConfig.devUrl = projectInfo.getDevUrl(syntheticalConfig.devEnvName);
syntheticalConfig.prodUrl = projectInfo.getProdUrl(syntheticalConfig.prodEnvName); // 接口列表
_context6.next = 7;
return _this3.fetchInterfaceList(syntheticalConfig);
case 7:
interfaceList = _context6.sent;
interfaceList = interfaceList.map(function (interfaceInfo) {
// 实现 _project 字段
interfaceInfo._project = omit(projectInfo, ['cats', 'getMockUrl', 'getDevUrl', 'getProdUrl']); // 预处理
// 预处理
var _interfaceInfo = isFunction(syntheticalConfig.preproccessInterface) ? syntheticalConfig.preproccessInterface(cloneDeepFast(interfaceInfo), changeCase, syntheticalConfig) : interfaceInfo;
return _interfaceInfo;
}).filter(Boolean);
interfaceList.sort(function (a, b) {
return a._id - b._id;
});
_context6.next = 12;
return Promise.all(interfaceList.map( /*#__PURE__*/function () {
var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(interfaceInfo) {
var outputFilePath, categoryUID, code, weights;
return _regeneratorRuntime.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
outputFilePath = path.resolve(_this3.options.cwd, typeof syntheticalConfig.outputFilePath === 'function' ? syntheticalConfig.outputFilePath(interfaceInfo, changeCase) : syntheticalConfig.outputFilePath);
categoryUID = "_" + serverIndex + "_" + projectIndex + "_" + categoryIndex + "_" + categoryIndex2;
_context5.next = 4;
return _this3.generateInterfaceCode(syntheticalConfig, interfaceInfo, categoryUID);
case 4:
code = _context5.sent;
weights = [serverIndex, projectIndex, categoryIndex, categoryIndex2];
return _context5.abrupt("return", {
categoryUID: categoryUID,
outputFilePath: outputFilePath,
weights: weights,
code: code
});
case 7:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
return function (_x12) {
return _ref12.apply(this, arguments);
};
}()));
case 12:
interfaceCodes = _context6.sent;
groupedInterfaceCodes = groupBy(interfaceCodes, function (item) {
return item.outputFilePath;
});
return _context6.abrupt("return", Object.keys(groupedInterfaceCodes).map(function (outputFilePath) {
var categoryCode = [].concat(uniq(sortByWeights(groupedInterfaceCodes[outputFilePath]).map(function (item) {
return item.categoryUID;
})).map(function (categoryUID) {
return syntheticalConfig.typesOnly ? '' : dedent(_templateObject || (_templateObject = _taggedTemplateLiteralLoose(["\n const mockUrl", " = ", " as any\n const devUrl", " = ", " as any\n const prodUrl", " = ", " as any\n const dataKey", " = ", " as any\n "])), categoryUID, JSON.stringify(syntheticalConfig.mockUrl), categoryUID, JSON.stringify(syntheticalConfig.devUrl), categoryUID, JSON.stringify(syntheticalConfig.prodUrl), categoryUID, JSON.stringify(syntheticalConfig.dataKey));
}), sortByWeights(groupedInterfaceCodes[outputFilePath]).map(function (item) {
return item.code;
})).filter(Boolean).join('\n\n');
if (!outputFileList[outputFilePath]) {
outputFileList[outputFilePath] = {
syntheticalConfig: syntheticalConfig,
content: [],
requestFunctionFilePath: syntheticalConfig.requestFunctionFilePath ? path.resolve(_this3.options.cwd, syntheticalConfig.requestFunctionFilePath) : path.join(path.dirname(outputFilePath), 'request.ts'),
requestHookMakerFilePath: syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled ? syntheticalConfig.reactHooks.requestHookMakerFilePath ? path.resolve(_this3.options.cwd, syntheticalConfig.reactHooks.requestHookMakerFilePath) : path.join(path.dirname(outputFilePath), 'makeRequestHook.ts') : ''
};
}
return {
outputFilePath: outputFilePath,
code: categoryCode,
weights: last(sortByWeights(groupedInterfaceCodes[outputFilePath])).weights
};
}));
case 15:
case "end":
return _context6.stop();
}
}
}, _callee6);
}));
return function (_x10, _x11) {
return _ref11.apply(this, arguments);
};
}()));
case 9:
codes = _context7.sent.flat();
for (_iterator = _createForOfIteratorHelperLoose(values(groupBy(codes, function (item) {
return item.outputFilePath;
}))); !(_step = _iterator()).done;) {
groupedCodes = _step.value;
sortByWeights(groupedCodes);
(_outputFileList$group = outputFileList[groupedCodes[0].outputFilePath].content).push.apply(_outputFileList$group, groupedCodes.map(function (item) {
return item.code;
}));
}
case 11:
case "end":
return _context7.stop();
}
}
}, _callee7);
}));
return function (_x8, _x9) {
return _ref10.apply(this, arguments);
};
}()));
case 5:
case "end":
return _context8.stop();
}
}
}, _callee8);
}));
return function (_x6, _x7) {
return _ref9.apply(this, arguments);
};
}())));
case 2:
case "end":
return _context9.stop();
}
}
}, _callee9);
}));
return function (_x4, _x5) {
return _ref8.apply(this, arguments);
};
}()));
case 3:
return _context10.abrupt("return", outputFileList);
case 4:
case "end":
return _context10.stop();
}
}
}, _callee10, this);
}));
function generate() {
return _generate.apply(this, arguments);
}
return generate;
}();
_proto.write = /*#__PURE__*/function () {
var _write = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(outputFileList) {
var _this4 = this;
return _regeneratorRuntime.wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
return _context12.abrupt("return", Promise.all(Object.keys(outputFileList).map( /*#__PURE__*/function () {
var _ref13 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(outputFilePath) {
var _outputFileList$outpu, content, requestFunctionFilePath, requestHookMakerFilePath, syntheticalConfig, rawRequestFunctionFilePath, rawRequestHookMakerFilePath, rawOutputContent, prettier, prettyOutputContent, outputContent;
return _regeneratorRuntime.wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
_outputFileList$outpu = outputFileList[outputFilePath], content = _outputFileList$outpu.content, requestFunctionFilePath = _outputFileList$outpu.requestFunctionFilePath, requestHookMakerFilePath = _outputFileList$outpu.requestHookMakerFilePath, syntheticalConfig = _outputFileList$outpu.syntheticalConfig;
rawRequestFunctionFilePath = requestFunctionFilePath;
rawRequestHookMakerFilePath = requestHookMakerFilePath; // 支持 .jsx? 后缀
// 支持 .jsx? 后缀
outputFilePath = outputFilePath.replace(/\.js(x)?$/, '.ts$1');
requestFunctionFilePath = requestFunctionFilePath.replace(/\.js(x)?$/, '.ts$1');
requestHookMakerFilePath = requestHookMakerFilePath.replace(/\.js(x)?$/, '.ts$1');
if (syntheticalConfig.typesOnly) {
_context11.next = 20;
break;
}
_context11.next = 9;
return fs.pathExists(rawRequestFunctionFilePath);
case 9:
if (_context11.sent) {
_context11.next = 12;
break;
}
_context11.next = 12;
return fs.outputFile(requestFunctionFilePath, dedent(_templateObject2 || (_templateObject2 = _taggedTemplateLiteralLoose(["\n import type { RequestFunctionParams } from 'yapi-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 const baseUrl = options.server === 'mock'\n ? payload.mockUrl\n : options.server === 'dev'\n ? payload.devUrl\n : payload.prodUrl\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-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 const baseUrl = options.server === 'mock'\n ? payload.mockUrl\n : options.server === 'dev'\n ? payload.devUrl\n : payload.prodUrl\n\n // \u8BF7\u6C42\u5730\u5740\n const url = \\`\\${baseUrl}\\${payload.path}\\`\n\n // \u5177\u4F53\u8BF7\u6C42\u903B\u8F91\n })\n }\n "]))));
case 12:
_context11.t0 = syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled;
if (!_context11.t0) {
_context11.next = 17;
break;
}
_context11.next = 16;
return fs.pathExists(rawRequestHookMakerFilePath);
case 16:
_context11.t0 = !_context11.sent;
case 17:
if (!_context11.t0) {
_context11.next = 20;
break;
}
_context11.next = 20;
return fs.outputFile(requestHookMakerFilePath, dedent(_templateObject3 || (_templateObject3 = _taggedTemplateLiteralLoose(["\n import { useState, useEffect } from 'react'\n import type { RequestConfig } from 'yapi-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))));
case 20:
// 始终写入主文件
rawOutputContent = dedent(_templateObject4 || (_templateObject4 = _taggedTemplateLiteralLoose(["\n /* tslint:disable */\n /* eslint-disable */\n\n /* \u8BE5\u6587\u4EF6\u7531 yapi-to-typescript \u81EA\u52A8\u751F\u6210\uFF0C\u8BF7\u52FF\u76F4\u63A5\u4FEE\u6539\uFF01\uFF01\uFF01 */\n\n ", "\n "])), syntheticalConfig.typesOnly ? dedent(_templateObject5 || (_templateObject5 = _taggedTemplateLiteralLoose(["\n // @ts-ignore\n type FileData = File\n\n ", "\n "])), content.join('\n\n').trim()) : dedent(_templateObject6 || (_templateObject6 = _taggedTemplateLiteralLoose(["\n // @ts-ignore\n // prettier-ignore\n import { QueryStringArrayFormat, Method, RequestBodyType, ResponseBodyType, FileData, prepare } from 'yapi-to-typescript'\n // @ts-ignore\n // prettier-ignore\n import type { RequestConfig, RequestFunctionRestArgs } from 'yapi-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 "])), JSON.stringify(getNormalizedRelativePath(outputFilePath, requestFunctionFilePath)), !syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? '' : dedent(_templateObject7 || (_templateObject7 = _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
_context11.next = 23;
return getPrettier(_this4.options.cwd);
case 23:
prettier = _context11.sent;
_context11.t1 = prettier;
_context11.t2 = rawOutputContent;
_context11.t3 = _extends;
_context11.t4 = {};
_context11.next = 30;
return getCachedPrettierOptions();
case 30:
_context11.t5 = _context11.sent;
_context11.t6 = {
filepath: outputFilePath
};
_context11.t7 = (0, _context11.t3)(_context11.t4, _context11.t5, _context11.t6);
_context11.next = 35;
return _context11.t1.format.call(_context11.t1, _context11.t2, _context11.t7);
case 35:
prettyOutputContent = _context11.sent;
outputContent = dedent(_templateObject8 || (_templateObject8 = _taggedTemplateLiteralLoose(["\n /* prettier-ignore-start */\n ", "\n /* prettier-ignore-end */\n "])), prettyOutputContent) + "\n";
_context11.next = 39;
return fs.outputFile(outputFilePath, outputContent);
case 39:
if (!(syntheticalConfig.target === 'javascript')) {
_context11.next = 44;
break;
}
_context11.next = 42;
return _this4.tsc(outputFilePath);
case 42:
_context11.next = 44;
return Promise.all([fs.remove(requestFunctionFilePath).catch(noop), fs.remove(requestHookMakerFilePath).catch(noop), fs.remove(outputFilePath).catch(noop)]);
case 44:
case "end":
return _context11.stop();
}
}
}, _callee11);
}));
return function (_x14) {
return _ref13.apply(this, arguments);
};
}())));
case 1:
case "end":
return _context12.stop();
}
}
}, _callee12);
}));
function write(_x13) {
return _write.apply(this, arguments);
}
return write;
}();
_proto.tsc = /*#__PURE__*/function () {
var _tsc = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(file) {
var _this5 = this;
return _regeneratorRuntime.wrap(function _callee13$(_context13) {
while (1) {
switch (_context13.prev = _context13.next) {
case 0:
return _context13.abrupt("return", new Promise(function (resolve) {
// add this to fix bug that not-generator-file-on-window
var command = "" + (require('os').platform() === 'win32' ? 'node ' : '') + JSON.stringify(require.resolve("typescript/bin/tsc"));
exec(command + " --target ES2019 --module ESNext --jsx preserve --declaration --esModuleInterop " + JSON.stringify(file), {
cwd: _this5.options.cwd,
env: process.env
}, function () {
return resolve();
});
}));
case 1:
case "end":
return _context13.stop();
}
}
}, _callee13);
}));
function tsc(_x15) {
return _tsc.apply(this, arguments);
}
return tsc;
}();
_proto.fetchApi = /*#__PURE__*/function () {
var _fetchApi = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(url, query) {
var res;
return _regeneratorRuntime.wrap(function _callee14$(_context14) {
while (1) {
switch (_context14.prev = _context14.next) {
case 0:
_context14.next = 2;
return httpGet(url, query);
case 2:
res = _context14.sent;
/* istanbul ignore next */
if (res && res.errcode) {
throwError(res.errmsg + " [\u8BF7\u6C42\u5730\u5740: " + url + "] [\u8BF7\u6C42\u53C2\u6570: " + new URLSearchParams(query).toString() + "]");
}
return _context14.abrupt("return", res.data || res);
case 5:
case "end":
return _context14.stop();
}
}
}, _callee14);
}));
function fetchApi(_x16, _x17) {
return _fetchApi.apply(this, arguments);
}
return fetchApi;
}();
/** 获取分类的接口列表 */
_proto.fetchInterfaceList =
/*#__PURE__*/
function () {
var _fetchInterfaceList = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(_ref14) {
var serverUrl, token, id, category;
return _regeneratorRuntime.wrap(function _callee15$(_context15) {
while (1) {
switch (_context15.prev = _context15.next) {
case 0:
serverUrl = _ref14.serverUrl, token = _ref14.token, id = _ref14.id;
_context15.next = 3;
return this.fetchExport({
serverUrl: serverUrl,
token: token
});
case 3:
_context15.t0 = _context15.sent;
if (_context15.t0) {
_context15.next = 6;
break;
}
_context15.t0 = [];
case 6:
category = _context15.t0.find(function (cat) {
return !isEmpty(cat) && !isEmpty(cat.list) && cat.list[0].catid === id;
});
if (category) {
category.list.forEach(function (interfaceInfo) {
// 实现 _category 字段
interfaceInfo._category = omit(category, ['list']);
});
}
return _context15.abrupt("return", category ? category.list : []);
case 9:
case "end":
return _context15.stop();
}
}
}, _callee15, this);
}));
function fetchInterfaceList(_x18) {
return _fetchInterfaceList.apply(this, arguments);
}
return fetchInterfaceList;
}()
/** 获取项目信息 */
;
_proto.fetchProjectInfo =
/*#__PURE__*/
function () {
var _fetchProjectInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee16(syntheticalConfig) {
var projectInfo, projectCats;
return _regeneratorRuntime.wrap(function _callee16$(_context16) {
while (1) {
switch (_context16.prev = _context16.next) {
case 0:
_context16.next = 2;
return this.fetchProject(syntheticalConfig);
case 2:
projectInfo = _context16.sent;
_context16.next = 5;
return this.fetchApi(syntheticalConfig.serverUrl + "/api/interface/getCatMenu", {
token: syntheticalConfig.token,
project_id: projectInfo._id
});
case 5:
projectCats = _context16.sent;
return _context16.abrupt("return", _extends({}, projectInfo, {
cats: projectCats,
getMockUrl: function getMockUrl() {
return syntheticalConfig.serverUrl + "/mock/" + projectInfo._id;
},
getDevUrl: function getDevUrl(devEnvName) {
var env = projectInfo.env.find(function (e) {
return e.name === devEnvName;
});
return env && env.domain
/* istanbul ignore next */
|| '';
},
getProdUrl: function getProdUrl(prodEnvName) {
var env = projectInfo.env.find(function (e) {
return e.name === prodEnvName;
});
return env && env.domain
/* istanbul ignore next */
|| '';
}
}));
case 7:
case "end":
return _context16.stop();
}
}
}, _callee16, this);
}));
function fetchProjectInfo(_x19) {
return _fetchProjectInfo.apply(this, arguments);
}
return fetchProjectInfo;
}()
/** 生成接口代码 */
;
_proto.generateInterfaceCode =
/*#__PURE__*/
function () {
var _generateInterfaceCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee17(syntheticalConfig, interfaceInfo, categoryUID) {
var _syntheticalConfig$js, _syntheticalConfig$js2, _syntheticalConfig$js3, _syntheticalConfig$js4;
var extendedInterfaceInfo, requestFunctionName, requestConfigName, requestConfigTypeName, requestDataTypeName, responseDataTypeName, requestDataJsonSchema, requestDataType, responseDataJsonSchema, responseDataType, isRequestDataOptional, requestHookName, paramNames, paramNamesLiteral, paramNameType, queryNames, queryNamesLiteral, queryNameType, genComment, requestFunctionExtraInfo;
return _regeneratorRuntime.wrap(function _callee17$(_context17) {
while (1) {
switch (_context17.prev = _context17.next) {
case 0:
extendedInterfaceInfo = _extends({}, interfaceInfo, {
parsedPath: path.parse(interfaceInfo.path)
});
if (!isFunction(syntheticalConfig.getRequestFunctionName)) {
_context17.next = 7;
break;
}
_context17.next = 4;
return syntheticalConfig.getRequestFunctionName(extendedInterfaceInfo, changeCase);
case 4:
_context17.t0 = _context17.sent;
_context17.next = 8;
break;
case 7:
_context17.t0 = changeCase.camelCase(extendedInterfaceInfo.parsedPath.name);
case 8:
requestFunctionName = _context17.t0;
requestConfigName = changeCase.camelCase(requestFunctionName + "RequestConfig");
requestConfigTypeName = changeCase.pascalCase(requestConfigName);
if (!isFunction(syntheticalConfig.getRequestDataTypeName)) {
_context17.next = 17;
break;
}
_context17.next = 14;
return syntheticalConfig.getRequestDataTypeName(extendedInterfaceInfo, changeCase);
case 14:
_context17.t1 = _context17.sent;
_context17.next = 18;
break;
case 17:
_context17.t1 = changeCase.pascalCase(requestFunctionName + "Request");
case 18:
requestDataTypeName = _context17.t1;
if (!isFunction(syntheticalConfig.getResponseDataTypeName)) {
_context17.next = 25;
break;
}
_context17.next = 22;
return syntheticalConfig.getResponseDataTypeName(extendedInterfaceInfo, changeCase);
case 22:
_context17.t2 = _context17.sent;
_context17.next = 26;
break;
case 25:
_context17.t2 = changeCase.pascalCase(requestFunctionName + "Response");
case 26:
responseDataTypeName = _context17.t2;
requestDataJsonSchema = getRequestDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {});
_context17.next = 30;
return jsonSchemaToType(requestDataJsonSchema, requestDataTypeName);
case 30: