UNPKG

openapi-ts-request

Version:

Swagger2/OpenAPI3/Apifox to TypeScript/JavaScript, request client(support any client), request mock service, enum and enum translation, react-query/vue-query, type field label, JSON Schemas

203 lines (201 loc) 7.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mockGenerator = void 0; const tslib_1 = require("tslib"); const fs_1 = tslib_1.__importDefault(require("fs")); const lodash_1 = require("lodash"); const mockjs_1 = tslib_1.__importDefault(require("mockjs")); const path_1 = require("path"); const tiny_pinyin_1 = tslib_1.__importDefault(require("tiny-pinyin")); const log_1 = tslib_1.__importDefault(require("../log")); const index_1 = tslib_1.__importDefault(require("../parser-mock/index")); const util_1 = require("../parser-mock/util"); const config_1 = require("./config"); const file_1 = require("./file"); mockjs_1.default.Random.extend({ country() { const data = [ '阿根廷', '澳大利亚', '巴西', '加拿大', '中国', '法国', '德国', '印度', '印度尼西亚', '意大利', '日本', '韩国', '墨西哥', '俄罗斯', '沙特阿拉伯', '南非', '土耳其', '英国', '美国', ]; return data[(0, util_1.getRandomInt)(0, data.length)]; }, phone() { const phonepreFix = ['111', '112', '114', '136', '170', '180', '183']; return (phonepreFix[(0, util_1.getRandomInt)(0, phonepreFix.length)] + mockjs_1.default.mock(/\d{8}/)); }, status() { const status = ['success', 'error', 'default', 'processing', 'warning']; return status[(0, util_1.getRandomInt)(0, status.length)]; }, authority() { const authority = ['admin', 'user', 'guest']; return authority[(0, util_1.getRandomInt)(0, authority.length)]; }, avatar() { const avatar = [ 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg', 'https://gw.alipayobjects.com/zos/rmsportal/udxAbMEhpwthVVcjLXik.png', 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png', 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png', 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png', 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4', 'https://avatars1.githubusercontent.com/u/8186664?s=40&v=4', ]; return avatar[(0, util_1.getRandomInt)(0, avatar.length)]; }, group() { const data = [ '体验技术部', '创新科技组', '前端 6 组', '区块链平台部', '服务技术部', ]; return data[(0, util_1.getRandomInt)(0, data.length)]; }, label() { const label = [ '很有想法的', '小清新', '傻白甜', '阳光少年', '大咖', '健身达人', '程序员', '算法工程师', '川妹子', '名望程序员', '大长腿', '海纳百川', '专注设计', '爱好广泛', 'IT 互联网', ]; return label[(0, util_1.getRandomInt)(0, label.length)]; }, href() { const href = [ 'https://preview.pro.ant.design/dashboard/analysis', 'https://ant.design', 'https://procomponents.ant.design/', 'https://umijs.org/', 'https://github.com/umijs/dumi', ]; return href[(0, util_1.getRandomInt)(0, href.length)]; }, }); const genMockData = (example) => { if (!example) { return {}; } if (typeof example === 'string') { return mockjs_1.default.mock(example); } if (Array.isArray(example)) { return mockjs_1.default.mock(example); } return Object.keys(example) .map((name) => { return { [name]: mockjs_1.default.mock(example[name]), }; }) .reduce((pre, next) => { return Object.assign(Object.assign({}, pre), next); }, {}); }; const genByTemp = ({ method, path, parameters, status, data, }) => { if (!(0, lodash_1.includes)(config_1.methods, method.toLocaleLowerCase())) { return ''; } let securityPath = path; (0, lodash_1.forEach)(parameters, (item) => { if (item.in === 'path') { securityPath = securityPath.replace(`{${item.name}}`, `:${item.name}`); } }); return `'${method.toUpperCase()} ${securityPath}': (req: Request, res: Response) => { res.status(${status}).send(${data}); }`; }; const genMockFiles = (mockFunction) => { return (0, file_1.prettierFile)(` /* eslint-disable */ // @ts-ignore import { Request, Response } from 'express'; export default { ${mockFunction.join('\n,')} }`)[0]; }; const mockGenerator = ({ openAPI, mockFolder, }) => { const openAPIParse = new index_1.default(openAPI); const docs = openAPIParse.parser(); const pathList = (0, lodash_1.keys)(docs.paths); const { paths } = docs; const mockActionsObj = {}; pathList.forEach((path) => { const pathConfig = paths[path]; (0, lodash_1.keys)(pathConfig).forEach((method) => { var _a, _b, _c; const methodConfig = pathConfig[method]; if (methodConfig) { let conte = (_b = (methodConfig.operationId || ((_a = methodConfig === null || methodConfig === void 0 ? void 0 : methodConfig.tags) === null || _a === void 0 ? void 0 : _a.join('/')) || path.replace('/', '').split('/')[1])) === null || _b === void 0 ? void 0 : _b.replace(/[^\w^\s^\u4e00-\u9fa5]/gi, ''); if (/[\u3220-\uFA29]/.test(conte)) { conte = tiny_pinyin_1.default.convertToPinyin(conte, '', true); } if (!conte) { return; } const response = (_c = methodConfig.responses) === null || _c === void 0 ? void 0 : _c['200']; const data = genMockData(response === null || response === void 0 ? void 0 : response.example); if (!mockActionsObj[conte]) { mockActionsObj[conte] = []; } const tempFile = genByTemp({ method, path, parameters: methodConfig.parameters, status: '200', data: JSON.stringify(data), }); if (tempFile) { mockActionsObj[conte].push(tempFile); } } }); }); Object.keys(mockActionsObj).forEach((file) => { if (!file || (0, lodash_1.isUndefined)(file)) { return; } if (file.includes('/')) { const dirName = (0, path_1.dirname)((0, path_1.join)(mockFolder, `${file}.mock.ts`)); if (!fs_1.default.existsSync(dirName)) { fs_1.default.mkdirSync(dirName); } } (0, file_1.writeFile)(mockFolder, `${file}.mock.ts`, genMockFiles(mockActionsObj[file])); }); (0, log_1.default)('✅ 生成 mock 文件成功'); }; exports.mockGenerator = mockGenerator;