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({
res.status(200).send({
data: [
{
key: 77,
disabled: true,
href: 'https://umijs.org/',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
name: '杜明',
owner: 'Johnson',
desc: '展金习设许此备还育住第即但没新何进。',
......@@ -39,7 +38,8 @@ module.exports = {
key: 98,
disabled: true,
href: 'https://procomponents.ant.design/',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
name: '韩军',
owner: 'Hall',
desc: '二应据称感号单常强持社少便快极西流能。',
......@@ -53,7 +53,8 @@ module.exports = {
key: 94,
disabled: false,
href: 'https://preview.pro.ant.design/dashboard/analysis',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
name: '刘平',
owner: 'Lopez',
desc: '大管别消证物拉主今解过格科家角。',
......@@ -67,7 +68,8 @@ module.exports = {
key: 74,
disabled: true,
href: 'https://ant.design',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
name: '苏娟',
owner: 'Miller',
desc: '需八相严平写今的快验二历林。',
......@@ -168,13 +170,12 @@ module.exports = {
});
},
'POST /api/rule': (req, res) => {
res
.status(200)
.send({
res.status(200).send({
key: 71,
disabled: true,
href: 'https://ant.design',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
name: '段勇',
owner: 'Thomas',
desc: '院题质数下布进或会府速体快型前快。',
......@@ -186,9 +187,7 @@ module.exports = {
});
},
'PUT /api/rule': (req, res) => {
res
.status(200)
.send({
res.status(200).send({
key: 94,
disabled: true,
href: 'https://umijs.org/',
......
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);
......
const chalk = require('chalk');
const Log = (...rest) => console.log(`${chalk.blue('[openAPI]')}: ${rest.join('\n')}`);
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 = [
......@@ -56,7 +56,13 @@ mockjs.Random.extend({
return avatar[id];
},
group() {
const data = ['体验技术部', '创新科技组', '前端 6 组', '区块链平台部', '服务技术部'];
const data = [
'体验技术部',
'创新科技组',
'前端 6 组',
'区块链平台部',
'服务技术部',
];
const id = (Math.random() * data.length).toFixed();
return data[id];
},
......@@ -93,7 +99,7 @@ mockjs.Random.extend({
return href[id];
},
});
const genMockData = (example) => {
const genMockData = example => {
if (!example) {
return {};
}
......@@ -104,50 +110,61 @@ const genMockData = (example) => {
return mockjs.mock(example);
}
return Object.keys(example)
.map((name) => {
return {
.map(name => ({
[name]: mockjs.mock(example[name]),
};
})
.reduce((pre, next) => {
return {
}))
.reduce(
(pre, next) => ({
...pre,
...next,
};
}, {});
}),
{},
);
};
const genByTemp = ({ method, path, status, data, }) => {
if (!['get', 'put', 'post', 'delete', 'patch'].includes(method.toLocaleLowerCase())) {
// 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 }) => {
// 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 = {};
pathList.forEach((path) => {
// eslint-disable-next-line no-shadow
pathList.forEach(path => {
const pathConfig = paths[path];
Object.keys(pathConfig).forEach((method) => {
Object.keys(pathConfig).forEach(method => {
const methodConfig = pathConfig[method];
if (methodConfig) {
const conte = methodConfig && methodConfig.tags && methodConfig.tags.join('/') ||
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);
const data = genMockData(
methodConfig &&
methodConfig.responses &&
methodConfig.responses['200'] &&
methodConfig.responses['200'].example,
);
if (!mockActionsObj[conte]) {
mockActionsObj[conte] = [];
}
......@@ -163,17 +180,21 @@ const mockGenerator = async ({ openAPI, mockFolder }) => {
}
});
});
Object.keys(mockActionsObj).forEach((file) => {
Object.keys(mockActionsObj).forEach(file => {
if (!file || file === 'undefined') {
return;
}
fs.writeFileSync(path.join(mockFolder, `${file}.mock.js`), genMockFiles(mockActionsObj[file]), {
fs.writeFileSync(
path.join(mockFolder, `${file}.mock.js`),
genMockFiles(mockActionsObj[file]),
{
encoding: 'utf8',
});
},
);
});
log('✅ 生成 mock 文件成功');
};
module.exports = {
mockGenerator
mockGenerator,
};
......@@ -24,9 +24,11 @@ const getDateByName = (name, parentsKey) => {
if (name.toLocaleLowerCase().endsWith('id')) {
return 'uuid';
}
if (name.toLocaleLowerCase().endsWith('type') ||
if (
name.toLocaleLowerCase().endsWith('type') ||
name.toLocaleLowerCase().endsWith('key') ||
['key'].includes(name)) {
['key'].includes(name)
) {
return 'id';
}
if (name.toLocaleLowerCase().endsWith('label') || ['label'].includes(name)) {
......@@ -59,33 +61,37 @@ const getDateByName = (name, parentsKey) => {
if (['country'].includes(name)) {
return 'country';
}
if (['url', 'imageUrl', 'href'].includes(name) ||
if (
['url', 'imageUrl', 'href'].includes(name) ||
name.toLocaleLowerCase().endsWith('url') ||
name.toLocaleLowerCase().endsWith('urls') ||
name.toLocaleLowerCase().endsWith('image') ||
name.toLocaleLowerCase().endsWith('link')) {
name.toLocaleLowerCase().endsWith('link')
) {
return 'href';
}
if (name.toLocaleLowerCase().endsWith('errorcode')) {
return 'errorCode';
}
if (['type', 'status'].includes(name) ||
if (
['type', 'status'].includes(name) ||
name.toLocaleLowerCase().endsWith('status') ||
name.toLocaleLowerCase().endsWith('type')) {
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];
const value =
primitives[`${type}_${format || getDateByName(propsName)}`] ||
primitives[type];
if (typeof schema.example === 'undefined') {
return value || `Unknown Type: ${schema.type}`;
}
......@@ -102,19 +108,21 @@ class OpenAPIGeneratorMockJs {
if (!type) {
if (properties) {
type = 'object';
}
else if (items) {
} else if (items) {
type = 'array';
}
else {
} 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]);
obj[name] = this.sampleFromSchema(props[name], [
...(propsName || []),
name,
]);
}
if (additionalProperties === true) {
obj.additionalProp1 = {};
......@@ -122,7 +130,10 @@ class OpenAPIGeneratorMockJs {
}
if (additionalProperties) {
const additionalProps = utils.objectify(additionalProperties);
const additionalPropVal = this.sampleFromSchema(additionalProps, propsName);
const additionalPropVal = this.sampleFromSchema(
additionalProps,
propsName,
);
for (let i = 1; i < 4; i += 1) {
obj[`additionalProp${i}`] = additionalPropVal;
}
......@@ -131,11 +142,12 @@ class OpenAPIGeneratorMockJs {
}
if (type === 'array') {
const item = this.sampleFromSchema(items, propsName);
return new Array(parseInt((Math.random() * 20).toFixed(0), 10)).fill(item);
return new Array(parseInt((Math.random() * 20).toFixed(0), 10)).fill(
item,
);
}
if (localSchema.enum) {
if (localSchema.default)
return localSchema.default;
if (localSchema.default) return localSchema.default;
return utils.normalizeArray(localSchema.enum)[0];
}
if (type === 'file') {
......@@ -144,23 +156,28 @@ class OpenAPIGeneratorMockJs {
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 &&
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;
// 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;
......
......@@ -27,4 +27,4 @@ module.exports = {
number_float: '@float(60, 100, 3, 5)',
integer: '@integer(60, 100)',
boolean: '@boolean',
}
\ No newline at end of file
};
......@@ -3,8 +3,7 @@ function isObject(obj) {
}
function objectify(thing) {
if (!isObject(thing))
return {};
if (!isObject(thing)) return {};
return thing;
}
......@@ -20,8 +19,7 @@ function get(entity, path) {
}
function normalizeArray(arr) {
if (Array.isArray(arr))
return arr;
if (Array.isArray(arr)) return arr;
return [arr];
}
......@@ -48,5 +46,5 @@ module.exports = {
get,
normalizeArray,
isFunc,
inferSchema
}
\ No newline at end of file
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;
......@@ -325,6 +326,7 @@ class ServiceGenerator {
// prefix 变量
return `$\{${prefix}}${formattedPath}`;
};
return {
...newApi,
functionName,
......@@ -625,4 +627,4 @@ module.exports = {
getPath,
getGenInfo,
ServiceGenerator
}
\ No newline at end of file
};
......@@ -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');
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: {}
}
}
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(
......
......@@ -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(
......
......@@ -35,15 +35,29 @@ export const dyRoutes = routes => {
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