Commit 1a8bf461 authored by 邓晓峰's avatar 邓晓峰

fix: 修复openapi

parent e3a58a52
Pipeline #23702 skipped with stages
// @ts-ignore
//import { Request, Response } from 'express';
// import { Request, Response } from 'express';
module.exports = {};
// @ts-ignore
//import { Request, Response } from 'express';
// import { Request, Response } from 'express';
module.exports = {
'GET /api/rule': (req, res) => {
res
.status(200)
.send({
data: [
{
key: 77,
disabled: true,
href: 'https://umijs.org/',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
name: '杜明',
owner: 'Johnson',
desc: '展金习设许此备还育住第即但没新何进。',
callNo: 75,
status: 69,
updatedAt: 'z*GGqY',
createdAt: 'OgCEx15',
progress: 81,
},
{
key: 72,
disabled: true,
href: 'https://ant.design',
avatar: 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4',
name: '龙伟',
owner: 'Moore',
desc: '近区置世意史风品容等量引律养级马理。',
callNo: 72,
status: 63,
updatedAt: 'o%NS',
createdAt: 'HJo',
progress: 89,
},
{
key: 98,
disabled: true,
href: 'https://procomponents.ant.design/',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
name: '韩军',
owner: 'Hall',
desc: '二应据称感号单常强持社少便快极西流能。',
callNo: 82,
status: 71,
updatedAt: '2jgCyz',
createdAt: '&d$kEH',
progress: 70,
},
{
key: 94,
disabled: false,
href: 'https://preview.pro.ant.design/dashboard/analysis',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
name: '刘平',
owner: 'Lopez',
desc: '大管别消证物拉主今解过格科家角。',
callNo: 71,
status: 97,
updatedAt: 'u5Y',
createdAt: '4xJ5O',
progress: 78,
},
{
key: 74,
disabled: true,
href: 'https://ant.design',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
name: '苏娟',
owner: 'Miller',
desc: '需八相严平写今的快验二历林。',
callNo: 76,
status: 89,
updatedAt: 'Roob',
createdAt: 'hikM9o',
progress: 92,
},
{
key: 92,
disabled: false,
href: 'https://preview.pro.ant.design/dashboard/analysis',
avatar: 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4',
name: '赖霞',
owner: 'Taylor',
desc: '采众用我类拉标技政般酸往得。',
callNo: 79,
status: 78,
updatedAt: 'Af9Y%',
createdAt: 'n*M4H',
progress: 66,
},
{
key: 99,
disabled: false,
href: '',
avatar:
'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
name: '何杰',
owner: 'Young',
desc: '段除然到社包示上来化文将机思。',
callNo: 67,
status: 99,
updatedAt: 'v!T9b',
createdAt: '3NS@',
progress: 69,
},
{
key: 88,
disabled: false,
href: 'https://procomponents.ant.design/',
avatar: 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4',
name: '冯娟',
owner: 'Johnson',
desc: '公与起拉记龙应二家种定科。',
callNo: 68,
status: 96,
updatedAt: 'hV6*R6',
createdAt: 'FrTdqU',
progress: 71,
},
{
key: 66,
disabled: false,
href: 'https://github.com/umijs/dumi',
avatar: 'https://avatars1.githubusercontent.com/u/8186664?s=40&v=4',
name: '杜刚',
owner: 'Lewis',
desc: '收花领养克听关消克般时电自必需论。',
callNo: 72,
status: 98,
updatedAt: 's*t',
createdAt: 'uby3w',
progress: 68,
},
{
key: 71,
disabled: true,
href: 'https://procomponents.ant.design/',
avatar: 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4',
name: '戴芳',
owner: 'Jackson',
desc: '也天下京完指际保手上劳响什部多。',
callNo: 85,
status: 64,
updatedAt: 'YIzwv',
createdAt: 'x[Z',
progress: 86,
},
{
key: 63,
disabled: true,
href: 'https://procomponents.ant.design/',
avatar: 'https://avatars1.githubusercontent.com/u/8186664?s=40&v=4',
name: '赖艳',
owner: 'Brown',
desc: '之示气上你力表清力队气消全划山路。',
callNo: 72,
status: 66,
updatedAt: '(6U0',
createdAt: 'WVSoNJ',
progress: 84,
},
],
total: 99,
success: true,
});
res.status(200).send({
data: [
{
key: 77,
disabled: true,
href: 'https://umijs.org/',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
name: '杜明',
owner: 'Johnson',
desc: '展金习设许此备还育住第即但没新何进。',
callNo: 75,
status: 69,
updatedAt: 'z*GGqY',
createdAt: 'OgCEx15',
progress: 81,
},
{
key: 72,
disabled: true,
href: 'https://ant.design',
avatar: 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4',
name: '龙伟',
owner: 'Moore',
desc: '近区置世意史风品容等量引律养级马理。',
callNo: 72,
status: 63,
updatedAt: 'o%NS',
createdAt: 'HJo',
progress: 89,
},
{
key: 98,
disabled: true,
href: 'https://procomponents.ant.design/',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
name: '韩军',
owner: 'Hall',
desc: '二应据称感号单常强持社少便快极西流能。',
callNo: 82,
status: 71,
updatedAt: '2jgCyz',
createdAt: '&d$kEH',
progress: 70,
},
{
key: 94,
disabled: false,
href: 'https://preview.pro.ant.design/dashboard/analysis',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
name: '刘平',
owner: 'Lopez',
desc: '大管别消证物拉主今解过格科家角。',
callNo: 71,
status: 97,
updatedAt: 'u5Y',
createdAt: '4xJ5O',
progress: 78,
},
{
key: 74,
disabled: true,
href: 'https://ant.design',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
name: '苏娟',
owner: 'Miller',
desc: '需八相严平写今的快验二历林。',
callNo: 76,
status: 89,
updatedAt: 'Roob',
createdAt: 'hikM9o',
progress: 92,
},
{
key: 92,
disabled: false,
href: 'https://preview.pro.ant.design/dashboard/analysis',
avatar: 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4',
name: '赖霞',
owner: 'Taylor',
desc: '采众用我类拉标技政般酸往得。',
callNo: 79,
status: 78,
updatedAt: 'Af9Y%',
createdAt: 'n*M4H',
progress: 66,
},
{
key: 99,
disabled: false,
href: '',
avatar:
'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
name: '何杰',
owner: 'Young',
desc: '段除然到社包示上来化文将机思。',
callNo: 67,
status: 99,
updatedAt: 'v!T9b',
createdAt: '3NS@',
progress: 69,
},
{
key: 88,
disabled: false,
href: 'https://procomponents.ant.design/',
avatar: 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4',
name: '冯娟',
owner: 'Johnson',
desc: '公与起拉记龙应二家种定科。',
callNo: 68,
status: 96,
updatedAt: 'hV6*R6',
createdAt: 'FrTdqU',
progress: 71,
},
{
key: 66,
disabled: false,
href: 'https://github.com/umijs/dumi',
avatar: 'https://avatars1.githubusercontent.com/u/8186664?s=40&v=4',
name: '杜刚',
owner: 'Lewis',
desc: '收花领养克听关消克般时电自必需论。',
callNo: 72,
status: 98,
updatedAt: 's*t',
createdAt: 'uby3w',
progress: 68,
},
{
key: 71,
disabled: true,
href: 'https://procomponents.ant.design/',
avatar: 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4',
name: '戴芳',
owner: 'Jackson',
desc: '也天下京完指际保手上劳响什部多。',
callNo: 85,
status: 64,
updatedAt: 'YIzwv',
createdAt: 'x[Z',
progress: 86,
},
{
key: 63,
disabled: true,
href: 'https://procomponents.ant.design/',
avatar: 'https://avatars1.githubusercontent.com/u/8186664?s=40&v=4',
name: '赖艳',
owner: 'Brown',
desc: '之示气上你力表清力队气消全划山路。',
callNo: 72,
status: 66,
updatedAt: '(6U0',
createdAt: 'WVSoNJ',
progress: 84,
},
],
total: 99,
success: true,
});
},
'POST /api/rule': (req, res) => {
res
.status(200)
.send({
key: 71,
disabled: true,
href: 'https://ant.design',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
name: '段勇',
owner: 'Thomas',
desc: '院题质数下布进或会府速体快型前快。',
callNo: 91,
status: 88,
updatedAt: 'T$frcd',
createdAt: '#]MhT%',
progress: 79,
});
res.status(200).send({
key: 71,
disabled: true,
href: 'https://ant.design',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
name: '段勇',
owner: 'Thomas',
desc: '院题质数下布进或会府速体快型前快。',
callNo: 91,
status: 88,
updatedAt: 'T$frcd',
createdAt: '#]MhT%',
progress: 79,
});
},
'PUT /api/rule': (req, res) => {
res
.status(200)
.send({
key: 94,
disabled: true,
href: 'https://umijs.org/',
avatar: 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4',
name: '常桂英',
owner: 'Perez',
desc: '布华意王去消候研格作指称。',
callNo: 61,
status: 97,
updatedAt: 'ZX0wE7',
createdAt: 'mg%',
progress: 93,
});
res.status(200).send({
key: 94,
disabled: true,
href: 'https://umijs.org/',
avatar: 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4',
name: '常桂英',
owner: 'Perez',
desc: '布华意王去消候研格作指称。',
callNo: 61,
status: 97,
updatedAt: 'ZX0wE7',
createdAt: 'mg%',
progress: 93,
});
},
'DELETE /api/rule': (req, res) => {
res.status(200).send({});
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -98,9 +98,9 @@
"@ant-design/pro-utils": "^1.10.4",
"@babel/polyfill": "7.4.3",
"@babel/runtime": "^7.10.5",
"@wisdom-utils/components": "0.0.9",
"@wisdom-utils/components": "0.0.14",
"@wisdom-utils/runtime": "0.0.15",
"@wisdom-utils/utils": "0.0.44",
"@wisdom-utils/utils": "0.0.46",
"animate.css": "^4.1.1",
"antd": "^4.11.2",
"compression": "1.7.4",
......@@ -114,7 +114,7 @@
"js-cookie": "^2.2.1",
"kit_global_config": "^1.0.24",
"kit_logger": "^1.0.2",
"kit_utils": "^1.3.10",
"kit_utils": "^1.3.11",
"lodash": "4.17.11",
"minimist": "1.2.0",
"mqtt-client": "^1.0.11",
......
......@@ -60,6 +60,7 @@ const generateService = async ({ requestLibPath, schemaPath, mockFolder, ...rest
const requestImportStatement = getImportStatement(requestLibPath);
const serviceGenerator = new serviceGenerators.ServiceGenerator({
namespace: 'API',
basePath: openAPI.servers[0].url,
requestImportStatement,
...rest,
}, openAPI);
......@@ -77,4 +78,4 @@ const generateService = async ({ requestLibPath, schemaPath, mockFolder, ...rest
module.exports = {
generateService,
getSchema
}
\ No newline at end of file
}
const chalk = require('chalk');
const Log = (...rest) => console.log(`${chalk.blue('[openAPI]')}: ${rest.join('\n')}`);
module.exports = Log;
\ No newline at end of file
const Log = (...rest) =>
console.log(`${chalk.blue('[openAPI]')}: ${rest.join('\n')}`);
module.exports = Log;
const mockjs = require("mockjs");
const fs = require("fs");
const util = require("./util");
const path = require("path");
const openAPIParserMock = require("./openAPIParserMock/index");
const log = require("./log");
const mockjs = require('mockjs');
const fs = require('fs');
const path = require('path');
const util = require('./util');
const openAPIParserMock = require('./openAPIParserMock/index');
const log = require('./log');
mockjs.Random.extend({
country() {
const data = [
'阿根廷',
'澳大利亚',
'巴西',
'加拿大',
'中国',
'法国',
'德国',
'印度',
'印度尼西亚',
'意大利',
'日本',
'韩国',
'墨西哥',
'俄罗斯',
'沙特阿拉伯',
'南非',
'土耳其',
'英国',
'美国',
];
const id = (Math.random() * data.length).toFixed();
return data[id];
},
phone() {
const phonepreFix = ['111', '112', '114']; // 自己写前缀哈
return this.pick(phonepreFix) + mockjs.mock(/\d{8}/); // Number()
},
status() {
const status = ['success', 'error', 'default', 'processing', 'warning'];
return status[(Math.random() * 4).toFixed(0)];
},
authority() {
const status = ['admin', 'user', 'guest'];
return status[(Math.random() * status.length).toFixed(0)];
},
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',
];
const id = (Math.random() * avatar.length).toFixed();
return avatar[id];
},
group() {
const data = ['体验技术部', '创新科技组', '前端 6 组', '区块链平台部', '服务技术部'];
const id = (Math.random() * data.length).toFixed();
return data[id];
},
label() {
const label = [
'很有想法的',
'小清新',
'傻白甜',
'阳光少年',
'大咖',
'健身达人',
'程序员',
'算法工程师',
'川妹子',
'名望程序员',
'大长腿',
'海纳百川',
'专注设计',
'爱好广泛',
'IT 互联网',
];
const id = (Math.random() * label.length).toFixed();
return label[id];
},
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',
];
const id = (Math.random() * href.length).toFixed();
return href[id];
},
country() {
const data = [
'阿根廷',
'澳大利亚',
'巴西',
'加拿大',
'中国',
'法国',
'德国',
'印度',
'印度尼西亚',
'意大利',
'日本',
'韩国',
'墨西哥',
'俄罗斯',
'沙特阿拉伯',
'南非',
'土耳其',
'英国',
'美国',
];
const id = (Math.random() * data.length).toFixed();
return data[id];
},
phone() {
const phonepreFix = ['111', '112', '114']; // 自己写前缀哈
return this.pick(phonepreFix) + mockjs.mock(/\d{8}/); // Number()
},
status() {
const status = ['success', 'error', 'default', 'processing', 'warning'];
return status[(Math.random() * 4).toFixed(0)];
},
authority() {
const status = ['admin', 'user', 'guest'];
return status[(Math.random() * status.length).toFixed(0)];
},
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',
];
const id = (Math.random() * avatar.length).toFixed();
return avatar[id];
},
group() {
const data = [
'体验技术部',
'创新科技组',
'前端 6 组',
'区块链平台部',
'服务技术部',
];
const id = (Math.random() * data.length).toFixed();
return data[id];
},
label() {
const label = [
'很有想法的',
'小清新',
'傻白甜',
'阳光少年',
'大咖',
'健身达人',
'程序员',
'算法工程师',
'川妹子',
'名望程序员',
'大长腿',
'海纳百川',
'专注设计',
'爱好广泛',
'IT 互联网',
];
const id = (Math.random() * label.length).toFixed();
return label[id];
},
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',
];
const id = (Math.random() * href.length).toFixed();
return href[id];
},
});
const genMockData = (example) => {
if (!example) {
return {};
}
if (typeof example === 'string') {
return mockjs.mock(example);
}
if (Array.isArray(example)) {
return mockjs.mock(example);
}
return Object.keys(example)
.map((name) => {
return {
[name]: mockjs.mock(example[name]),
};
})
.reduce((pre, next) => {
return {
...pre,
...next,
};
}, {});
const genMockData = example => {
if (!example) {
return {};
}
if (typeof example === 'string') {
return mockjs.mock(example);
}
if (Array.isArray(example)) {
return mockjs.mock(example);
}
return Object.keys(example)
.map(name => ({
[name]: mockjs.mock(example[name]),
}))
.reduce(
(pre, next) => ({
...pre,
...next,
}),
{},
);
};
const genByTemp = ({ method, path, status, data, }) => {
if (!['get', 'put', 'post', 'delete', 'patch'].includes(method.toLocaleLowerCase())) {
return '';
}
return `'${method.toUpperCase()} ${path}': (req, res) => {
// eslint-disable-next-line no-shadow
const genByTemp = ({ method, path, status, data }) => {
if (
!['get', 'put', 'post', 'delete', 'patch'].includes(
method.toLocaleLowerCase(),
)
) {
return '';
}
return `'${method.toUpperCase()} ${path}': (req, res) => {
res.status(${status}).send(${data});
}`;
};
const genMockFiles = (mockFunction) => {
return util.prettierFile(`
const genMockFiles = mockFunction =>
util.prettierFile(`
// @ts-ignore
//import { Request, Response } from 'express';
module.exports = {
${mockFunction.join('\n,')}
}`)[0];
};
const mockGenerator = async ({ openAPI, mockFolder }) => {
const openAPParse = new openAPIParserMock(openAPI);
const docs = openAPParse.parser();
const pathList = Object.keys(docs.paths);
const { paths } = docs;
const mockActionsObj = {};
pathList.forEach((path) => {
const pathConfig = paths[path];
Object.keys(pathConfig).forEach((method) => {
const methodConfig = pathConfig[method];
if (methodConfig) {
const conte = methodConfig && methodConfig.tags && methodConfig.tags.join('/') ||
path.replace('/', '').split('/')[1] ||
methodConfig.operationId;
const data = genMockData(methodConfig && methodConfig.responses && methodConfig.responses['200'] && methodConfig.responses['200'].example);
if (!mockActionsObj[conte]) {
mockActionsObj[conte] = [];
}
const tempFile = genByTemp({
method,
path,
status: '200',
data: JSON.stringify(data),
});
if (tempFile) {
mockActionsObj[conte].push(tempFile);
}
}
});
});
Object.keys(mockActionsObj).forEach((file) => {
if (!file || file === 'undefined') {
return;
// eslint-disable-next-line new-cap
const openAPParse = new openAPIParserMock(openAPI);
const docs = openAPParse.parser();
const pathList = Object.keys(docs.paths);
const { paths } = docs;
const mockActionsObj = {};
// eslint-disable-next-line no-shadow
pathList.forEach(path => {
const pathConfig = paths[path];
Object.keys(pathConfig).forEach(method => {
const methodConfig = pathConfig[method];
if (methodConfig) {
const conte =
(methodConfig && methodConfig.tags && methodConfig.tags.join('/')) ||
path.replace('/', '').split('/')[1] ||
methodConfig.operationId;
const data = genMockData(
methodConfig &&
methodConfig.responses &&
methodConfig.responses['200'] &&
methodConfig.responses['200'].example,
);
if (!mockActionsObj[conte]) {
mockActionsObj[conte] = [];
}
fs.writeFileSync(path.join(mockFolder, `${file}.mock.js`), genMockFiles(mockActionsObj[file]), {
encoding: 'utf8',
const tempFile = genByTemp({
method,
path,
status: '200',
data: JSON.stringify(data),
});
if (tempFile) {
mockActionsObj[conte].push(tempFile);
}
}
});
log('✅ 生成 mock 文件成功');
});
Object.keys(mockActionsObj).forEach(file => {
if (!file || file === 'undefined') {
return;
}
fs.writeFileSync(
path.join(mockFolder, `${file}.mock.js`),
genMockFiles(mockActionsObj[file]),
{
encoding: 'utf8',
},
);
});
log('✅ 生成 mock 文件成功');
};
module.exports = {
mockGenerator
};
\ No newline at end of file
mockGenerator,
};
......@@ -3,175 +3,192 @@ const utils = require('./utils');
const primitives = require('./preimitives');
const getDateByName = (name, parentsKey) => {
if (!name || name.length < 1) {
return 'string';
}
if (Array.isArray(name)) {
return getDateByName([...name].pop(), name);
}
if (['nickname', 'name'].includes(name)) {
return 'cname';
}
if (['owner', 'firstName', 'lastName', 'username'].includes(name)) {
return 'name';
}
if (['avatar'].includes(name)) {
return 'avatar';
}
if (['group'].includes(name)) {
return 'group';
}
if (name.toLocaleLowerCase().endsWith('id')) {
return 'uuid';
}
if (name.toLocaleLowerCase().endsWith('type') ||
name.toLocaleLowerCase().endsWith('key') ||
['key'].includes(name)) {
return 'id';
}
if (name.toLocaleLowerCase().endsWith('label') || ['label'].includes(name)) {
const newParents = [...parentsKey];
newParents.pop();
const newType = getDateByName(newParents);
if (newType !== 'string' && newType !== 'csentence') {
return newType;
}
return 'label';
}
if (['email'].includes(name)) {
return 'email';
}
if (['password'].includes(name)) {
return 'string(16)';
}
if (['phone'].includes(name)) {
return 'phone';
}
if (['province'].includes(name)) {
return 'province';
}
if (['city'].includes(name)) {
return 'city';
}
if (['addr', 'address'].includes(name)) {
return 'county';
}
if (['country'].includes(name)) {
return 'country';
}
if (['url', 'imageUrl', 'href'].includes(name) ||
name.toLocaleLowerCase().endsWith('url') ||
name.toLocaleLowerCase().endsWith('urls') ||
name.toLocaleLowerCase().endsWith('image') ||
name.toLocaleLowerCase().endsWith('link')) {
return 'href';
}
if (name.toLocaleLowerCase().endsWith('errorcode')) {
return 'errorCode';
}
if (['type', 'status'].includes(name) ||
name.toLocaleLowerCase().endsWith('status') ||
name.toLocaleLowerCase().endsWith('type')) {
return 'status';
}
if (name.toLocaleLowerCase().endsWith('authority')) {
return 'authority';
}
return 'csentence';
}
if (!name || name.length < 1) {
return 'string';
}
if (Array.isArray(name)) {
return getDateByName([...name].pop(), name);
}
if (['nickname', 'name'].includes(name)) {
return 'cname';
}
if (['owner', 'firstName', 'lastName', 'username'].includes(name)) {
return 'name';
}
if (['avatar'].includes(name)) {
return 'avatar';
}
if (['group'].includes(name)) {
return 'group';
}
if (name.toLocaleLowerCase().endsWith('id')) {
return 'uuid';
}
if (
name.toLocaleLowerCase().endsWith('type') ||
name.toLocaleLowerCase().endsWith('key') ||
['key'].includes(name)
) {
return 'id';
}
if (name.toLocaleLowerCase().endsWith('label') || ['label'].includes(name)) {
const newParents = [...parentsKey];
newParents.pop();
const newType = getDateByName(newParents);
if (newType !== 'string' && newType !== 'csentence') {
return newType;
}
return 'label';
}
if (['email'].includes(name)) {
return 'email';
}
if (['password'].includes(name)) {
return 'string(16)';
}
if (['phone'].includes(name)) {
return 'phone';
}
if (['province'].includes(name)) {
return 'province';
}
if (['city'].includes(name)) {
return 'city';
}
if (['addr', 'address'].includes(name)) {
return 'county';
}
if (['country'].includes(name)) {
return 'country';
}
if (
['url', 'imageUrl', 'href'].includes(name) ||
name.toLocaleLowerCase().endsWith('url') ||
name.toLocaleLowerCase().endsWith('urls') ||
name.toLocaleLowerCase().endsWith('image') ||
name.toLocaleLowerCase().endsWith('link')
) {
return 'href';
}
if (name.toLocaleLowerCase().endsWith('errorcode')) {
return 'errorCode';
}
if (
['type', 'status'].includes(name) ||
name.toLocaleLowerCase().endsWith('status') ||
name.toLocaleLowerCase().endsWith('type')
) {
return 'status';
}
if (name.toLocaleLowerCase().endsWith('authority')) {
return 'authority';
}
return 'csentence';
};
function primitive(schemaParams, propsName) {
const schema = utils.objectify(schemaParams);
console.log("schemaParams", propsName)
const { type, format } = schema;
const value = primitives[`${type}_${format || getDateByName(propsName)}`] || primitives[type];
if (typeof schema.example === 'undefined') {
return value || `Unknown Type: ${schema.type}`;
}
return schema.example;
const schema = utils.objectify(schemaParams);
const { type, format } = schema;
const value =
primitives[`${type}_${format || getDateByName(propsName)}`] ||
primitives[type];
if (typeof schema.example === 'undefined') {
return value || `Unknown Type: ${schema.type}`;
}
return schema.example;
}
class OpenAPIGeneratorMockJs {
constructor(openAPI) {
this.sampleFromSchema = (schema, propsName) => {
const localSchema = schema.$ref
? utils.get(this.openAPI, schema.$ref.replace('#/', '').split('/'))
: utils.objectify(schema);
let { type } = localSchema;
const { properties, additionalProperties, items } = localSchema;
if (!type) {
if (properties) {
type = 'object';
}
else if (items) {
type = 'array';
}
else {
return null;
}
}
if (type === 'object') {
const props = utils.objectify(properties);
const obj = {};
for (const name in props) {
obj[name] = this.sampleFromSchema(props[name], [...(propsName || []), name]);
}
if (additionalProperties === true) {
obj.additionalProp1 = {};
return obj;
}
if (additionalProperties) {
const additionalProps = utils.objectify(additionalProperties);
const additionalPropVal = this.sampleFromSchema(additionalProps, propsName);
for (let i = 1; i < 4; i += 1) {
obj[`additionalProp${i}`] = additionalPropVal;
}
}
return obj;
}
if (type === 'array') {
const item = this.sampleFromSchema(items, propsName);
return new Array(parseInt((Math.random() * 20).toFixed(0), 10)).fill(item);
}
if (localSchema.enum) {
if (localSchema.default)
return localSchema.default;
return utils.normalizeArray(localSchema.enum)[0];
}
if (type === 'file') {
return null;
}
return primitive(localSchema, propsName);
};
this.parser = () => {
const openAPI = {
...this.openAPI,
};
for (const path in openAPI.paths) {
for (const method in openAPI.paths[path]) {
const api = openAPI.paths[path][method];
for (const code in api.responses) {
const response = api.responses[code];
const schema = response.content &&
response.content['application/json'] &&
utils.inferSchema(response.content['application/json']);
if (schema) {
response.example = schema ? this.sampleFromSchema(schema) : null;
}
}
if (!api.parameters)
continue;
for (const parameter of api.parameters) {
const schema = utils.inferSchema(parameter);
parameter.example = schema ? this.sampleFromSchema(schema) : null;
}
}
constructor(openAPI) {
this.sampleFromSchema = (schema, propsName) => {
const localSchema = schema.$ref
? utils.get(this.openAPI, schema.$ref.replace('#/', '').split('/'))
: utils.objectify(schema);
let { type } = localSchema;
const { properties, additionalProperties, items } = localSchema;
if (!type) {
if (properties) {
type = 'object';
} else if (items) {
type = 'array';
} else {
return null;
}
}
if (type === 'object') {
const props = utils.objectify(properties);
const obj = {};
// eslint-disable-next-line guard-for-in
for (const name in props) {
obj[name] = this.sampleFromSchema(props[name], [
...(propsName || []),
name,
]);
}
if (additionalProperties === true) {
obj.additionalProp1 = {};
return obj;
}
if (additionalProperties) {
const additionalProps = utils.objectify(additionalProperties);
const additionalPropVal = this.sampleFromSchema(
additionalProps,
propsName,
);
for (let i = 1; i < 4; i += 1) {
obj[`additionalProp${i}`] = additionalPropVal;
}
}
return obj;
}
if (type === 'array') {
const item = this.sampleFromSchema(items, propsName);
return new Array(parseInt((Math.random() * 20).toFixed(0), 10)).fill(
item,
);
}
if (localSchema.enum) {
if (localSchema.default) return localSchema.default;
return utils.normalizeArray(localSchema.enum)[0];
}
if (type === 'file') {
return null;
}
return primitive(localSchema, propsName);
};
this.parser = () => {
// eslint-disable-next-line no-shadow
const openAPI = {
...this.openAPI,
};
// eslint-disable-next-line guard-for-in
for (const path in openAPI.paths) {
// eslint-disable-next-line guard-for-in
for (const method in openAPI.paths[path]) {
const api = openAPI.paths[path][method];
// eslint-disable-next-line guard-for-in
for (const code in api.responses) {
const response = api.responses[code];
const schema =
response.content &&
response.content['application/json'] &&
utils.inferSchema(response.content['application/json']);
if (schema) {
response.example = schema ? this.sampleFromSchema(schema) : null;
}
return openAPI;
};
this.openAPI = openAPI;
this.sampleFromSchema = memoizee(this.sampleFromSchema);
}
}
// eslint-disable-next-line no-continue
if (!api.parameters) continue;
for (const parameter of api.parameters) {
const schema = utils.inferSchema(parameter);
parameter.example = schema ? this.sampleFromSchema(schema) : null;
}
}
}
return openAPI;
};
this.openAPI = openAPI;
this.sampleFromSchema = memoizee(this.sampleFromSchema);
}
}
module.exports = OpenAPIGeneratorMockJs;
\ No newline at end of file
module.exports = OpenAPIGeneratorMockJs;
module.exports = {
string: '@string',
string_email: '@email',
string_phone: '@phone',
string_username: '@cname',
string_url: '@url',
string_uuid: '@guid',
string_id: '@increment',
string_status: '@status',
string_authority: '@authority',
string_label: '@label',
string_group: '@group',
string_csentence: '@csentence',
string_cname: '@cname',
string_name: '@last',
string_errorCode: '@increment',
string_country: '@country',
string_county: '@county(true)',
string_province: '@province',
string_city: '@city',
string_avatar: '@avatar',
string_href: '@href',
'string_string(16)': 'string(16)',
'string_date-time': '@datetime',
string_date: '@date',
number: '@integer(60, 100)',
number_float: '@float(60, 100, 3, 5)',
integer: '@integer(60, 100)',
boolean: '@boolean',
}
\ No newline at end of file
string: '@string',
string_email: '@email',
string_phone: '@phone',
string_username: '@cname',
string_url: '@url',
string_uuid: '@guid',
string_id: '@increment',
string_status: '@status',
string_authority: '@authority',
string_label: '@label',
string_group: '@group',
string_csentence: '@csentence',
string_cname: '@cname',
string_name: '@last',
string_errorCode: '@increment',
string_country: '@country',
string_county: '@county(true)',
string_province: '@province',
string_city: '@city',
string_avatar: '@avatar',
string_href: '@href',
'string_string(16)': 'string(16)',
'string_date-time': '@datetime',
string_date: '@date',
number: '@integer(60, 100)',
number_float: '@float(60, 100, 3, 5)',
integer: '@integer(60, 100)',
boolean: '@boolean',
};
function isObject(obj) {
return !!obj && typeof obj === 'object';
return !!obj && typeof obj === 'object';
}
function objectify(thing) {
if (!isObject(thing))
return {};
return thing;
if (!isObject(thing)) return {};
return thing;
}
function get(entity, path) {
let current = entity;
for (let i = 0; i < path.length; i += 1) {
if (current === null || current === undefined) {
return undefined;
}
current = current[path[i]];
let current = entity;
for (let i = 0; i < path.length; i += 1) {
if (current === null || current === undefined) {
return undefined;
}
return current;
current = current[path[i]];
}
return current;
}
function normalizeArray(arr) {
if (Array.isArray(arr))
return arr;
return [arr];
if (Array.isArray(arr)) return arr;
return [arr];
}
function isFunc(thing) {
return typeof thing === 'function';
return typeof thing === 'function';
}
function inferSchema(thing) {
if (thing.schema) {
return thing.schema;
}
if (thing.properties) {
return {
...thing,
type: 'object',
};
}
return thing;
if (thing.schema) {
return thing.schema;
}
if (thing.properties) {
return {
...thing,
type: 'object',
};
}
return thing;
}
module.exports = {
isObject,
objectify,
get,
normalizeArray,
isFunc,
inferSchema
}
\ No newline at end of file
isObject,
objectify,
get,
normalizeArray,
isFunc,
inferSchema,
};
......@@ -21,9 +21,9 @@ function createMiddleware(config) {
if (serversFolder && !existsSync(serversFolder)) {
mkdirSync(serversFolder);
}
// pageConfig.name.split('/').pop(),
await generateService({
projectName: '',
//pageConfig.name.split('/').pop(),
...openAPIConfig,
serversPath: serversFolder,
mockFolder,
......
/* eslint-disable */
const fs = require('fs');
const glob = require('glob');
const rimraf = require('rimraf');
const nunjucks = require("nunjucks");
const nunjucks = require('nunjucks');
const path = require('path');
const lodash = require('lodash');
const reservedWords = require('reserved-words');
......@@ -159,7 +160,7 @@ class ServiceGenerator {
};
this.openAPIData = openAPIData;
const { info } = openAPIData;
const basePath = '';
const basePath = config.basePath || '';
this.version = info.version;
Object.keys(openAPIData.paths || {}).forEach((p) => {
const pathItem = openAPIData.paths[p];
......@@ -182,7 +183,7 @@ class ServiceGenerator {
});
}
genFile() {
const basePath = this.config.serversPath || './src/service';
const basePath = this.config.serversPath || './src/api/generateAPI';
try {
const finalPath = path.join(basePath, this.config.projectName);
this.finalPath = finalPath;
......@@ -229,7 +230,7 @@ class ServiceGenerator {
list: this.classNameList,
disableTypeCheck: false,
});
// 打印日志
log(`✅ 成功生成 service 文件`);
}
......@@ -239,7 +240,7 @@ class ServiceGenerator {
// functionName tag 级别防重
const tmpFunctionRD = {};
const genParams = this.apiData[tag]
.filter((api) =>
.filter((api) =>
// 暂不支持变量
!api.path.includes('${'))
.map((api) => {
......@@ -325,6 +326,7 @@ class ServiceGenerator {
// prefix 变量
return `$\{${prefix}}${formattedPath}`;
};
return {
...newApi,
functionName,
......@@ -622,7 +624,7 @@ class ServiceGenerator {
}
module.exports = {
getPath,
getGenInfo,
ServiceGenerator
}
\ No newline at end of file
getPath,
getGenInfo,
ServiceGenerator
};
......@@ -13,18 +13,11 @@ import 'sanitize.css/sanitize.css';
import React from 'react';
import ReactDOM from 'react-dom';
import {
Button,
message,
notification,
} from 'antd';
import { Button, message, notification } from 'antd';
import { ConnectedRouter } from 'connected-react-router/immutable';
import Immutable from 'immutable';
import Cookies from 'js-cookie';
import {
params,
Storeage,
} from 'kit_utils';
import { params, Storeage } from 'kit_utils';
import { Provider } from 'react-redux';
import { useIntl } from '@/locales/localeExports';
......@@ -42,15 +35,13 @@ import { actionCreators } from './containers/App/store';
import { LocaleContainer } from './locales/locale';
import { initMicroApps } from './micro';
import Login from './pages/user/login/login';
import {
getToken,
isString,
} from './utils/utils';
import { getToken, isString } from './utils/utils';
const isHttps = document.location.protocol === 'https:';
const { pwa } = defaultSettings;
// eslint-disable-next-line no-restricted-globals
const namespace = `__PANDA_STORE__${location.hostname}`;
debugger
window.createStoreage = new Storeage(namespace);
// eslint-disable-next-line no-underscore-dangle
const initialState = Immutable.Map();
......@@ -83,6 +74,8 @@ const initLocale = () => {
};
const initGlobalConfig = () => {
// eslint-disable-next-line no-debugger
debugger
// eslint-disable-next-line no-undef
let config = createStoreage.get('globalConfig') || {};
store.dispatch(actionCreators.updateComplexConfig({}));
......@@ -188,15 +181,7 @@ window.share &&
window.share.event.on('triggerMicro', () => {
initMicroApps(loader, store);
});
window.share &&
window.share.event &&
window.share.event.on('triggerLoginout', () => {
if(Cookies.get('token')) {
store.dispatch(actionCreators.logout());
window.location.reload();
}
initGlobalConfig();
});
if (pwa) {
// const appPWA = window.i18n.getI18n('app');
......
......@@ -163,10 +163,13 @@ export function updateMicroMounted(data) {
}
export function logout(data) {
// eslint-disable-next-line no-undef
createStoreage.remove('PANDA_STORE');
Cookies.set(window.globalConfig.client, '', {
path: '/',
});
if (window.globalConfig) {
Cookies.set(window.globalConfig.client, '', {
path: '/',
});
}
Cookies.set('token', '', {
path: '/',
......@@ -183,13 +186,13 @@ export function logout(data) {
path: '/',
});
localStorage.removeItem('access_token');
// eslint-disable-next-line no-undef,no-restricted-globals
createStoreage.remove(`__PANDA_STORE__${location.hostname}`);
return {
type: LOGINOUT,
data: {
currentMenuIndex: 0,
// config: {},
complexConfig: {}
}
}
}
\ No newline at end of file
complexConfig: {},
},
};
}
......@@ -198,7 +198,7 @@ const appReducer = (state = initialState, action) => {
return state.merge({
complexConfig: action.data.complexConfig,
currentMenuIndex: action.data.currentMenuIndex,
})
});
default:
return state;
}
......
......@@ -50,7 +50,7 @@ export const initMicroApps = (loader, store) => {
item.activeRule = genActiveRule(`/civbase/${item.PackageName}`);
item.props = JSON.parse(item.DefaultSetting);
return item;
})
}) || micorConfig.prod
: micorConfig.prod;
registerMicroApps(
......@@ -276,4 +276,4 @@ window.app.define('rc-tree', require.context('../node_modules/rc-tree/lib', true
window.app.define('rc-tree-select', require.context('../node_modules/rc-tree-select/lib', true, /^.\/(lib\/)?[^\/]+\.js$/), 'index.js');
window.app.define('rc-trigger', require.context('../node_modules/rc-trigger/lib', true, /^.\/(lib\/)?[^\/]+\.js$/), 'index.js');
window.app.define('rc-upload', require.context('../node_modules/rc-upload/lib', true, /^.\/(lib\/)?[^\/]+\.js$/), 'index.js');
window.app.define('rc-virtual-list', require.context('../node_modules/rc-virtual-list/lib', true, /^.\/(lib\/)?[^\/]+\.js$/), 'index.js');
\ No newline at end of file
window.app.define('rc-virtual-list', require.context('../node_modules/rc-virtual-list/lib', true, /^.\/(lib\/)?[^\/]+\.js$/), 'index.js');
......@@ -9,7 +9,9 @@ export default () => {
switch(loginTemplate) {
case '新春 - 智联.html':
return <NewYear/>
default:
case 'Dark.html':
return <BaseLogin/>
default:
return <></>;
}
};
import 'kit_utils/lib/format';
import React, {
forwardRef,
useEffect,
useRef,
useState,
} from 'react';
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import {
Alert,
Checkbox,
Form,
Modal,
Popover,
} from 'antd';
import { Alert, Checkbox, Form, Modal, Popover } from 'antd';
import classNames from 'classnames';
import { encode } from 'js-base64';
import Cookies from 'js-cookie';
import { dom } from 'kit_utils';
import QRCode from 'qrcode.react';
import {
Helmet,
HelmetProvider,
} from 'react-helmet-async';
import { Helmet, HelmetProvider } from 'react-helmet-async';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import {
LOGIN_DISPLAY,
LOGIN_WAY,
} from '@/constants';
import { LOGIN_DISPLAY, LOGIN_WAY } from '@/constants';
import { actionCreators } from '@/containers/App/store';
import { useIntl } from '@/locales/localeExports';
......@@ -556,7 +539,7 @@ const Login = forwardRef((props, _ref) => {
>
<img
role="logo"
src={props.global.transformDevAssetsBaseURL(props.global.logo)}
src={props.global && props.global.transformDevAssetsBaseURL && props.global.transformDevAssetsBaseURL(props.global.logo)}
/>
<div
className={classNames(
......
......@@ -31,19 +31,33 @@ export const dyRoutes = routes => {
component: BasicLayout,
routes: dyRoutes,
},
process.env.NODE_ENV === 'development' && {
path: '/openapi',
exact: true,
component: dynamic({ loader: () => import(/* webpackChunkName: 'civ__plugin-openapi__openapi' */'../components/openapi/openapi'), loading: LoadingComponent}),
component: dynamic({
loader: () =>
import(
/* webpackChunkName: 'civ__plugin-openapi__openapi' */ '../components/openapi/openapi'
),
loading: LoadingComponent,
}),
},
{
path: '/404',
component: dynamic({ loader: () => import(/* webpackChunkName: 'p__404' */'../pages/exception/404'), loading: LoadingComponent}),
component: dynamic({
loader: () =>
import(/* webpackChunkName: 'p__404' */ '../pages/exception/404'),
loading: LoadingComponent,
}),
},
{
path: '/500',
component: dynamic({ loader: () => import(/* webpackChunkName: 'p__500' */'../pages/exception/500'), loading: LoadingComponent}),
component: dynamic({
loader: () =>
import(/* webpackChunkName: 'p__500' */ '../pages/exception/500'),
loading: LoadingComponent,
}),
},
],
};
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment