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

fix: 修复openapi

parent e3a58a52
Pipeline #23702 skipped with stages
// @ts-ignore // @ts-ignore
//import { Request, Response } from 'express'; // import { Request, Response } from 'express';
module.exports = {}; module.exports = {};
// @ts-ignore // @ts-ignore
//import { Request, Response } from 'express'; // import { Request, Response } from 'express';
module.exports = { module.exports = {
'GET /api/rule': (req, res) => { 'GET /api/rule': (req, res) => {
res res.status(200).send({
.status(200)
.send({
data: [ data: [
{ {
key: 77, key: 77,
disabled: true, disabled: true,
href: 'https://umijs.org/', href: 'https://umijs.org/',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png', avatar:
'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
name: '杜明', name: '杜明',
owner: 'Johnson', owner: 'Johnson',
desc: '展金习设许此备还育住第即但没新何进。', desc: '展金习设许此备还育住第即但没新何进。',
...@@ -39,7 +38,8 @@ module.exports = { ...@@ -39,7 +38,8 @@ module.exports = {
key: 98, key: 98,
disabled: true, disabled: true,
href: 'https://procomponents.ant.design/', href: 'https://procomponents.ant.design/',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png', avatar:
'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
name: '韩军', name: '韩军',
owner: 'Hall', owner: 'Hall',
desc: '二应据称感号单常强持社少便快极西流能。', desc: '二应据称感号单常强持社少便快极西流能。',
...@@ -53,7 +53,8 @@ module.exports = { ...@@ -53,7 +53,8 @@ module.exports = {
key: 94, key: 94,
disabled: false, disabled: false,
href: 'https://preview.pro.ant.design/dashboard/analysis', 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: '刘平', name: '刘平',
owner: 'Lopez', owner: 'Lopez',
desc: '大管别消证物拉主今解过格科家角。', desc: '大管别消证物拉主今解过格科家角。',
...@@ -67,7 +68,8 @@ module.exports = { ...@@ -67,7 +68,8 @@ module.exports = {
key: 74, key: 74,
disabled: true, disabled: true,
href: 'https://ant.design', href: 'https://ant.design',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg', avatar:
'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
name: '苏娟', name: '苏娟',
owner: 'Miller', owner: 'Miller',
desc: '需八相严平写今的快验二历林。', desc: '需八相严平写今的快验二历林。',
...@@ -168,13 +170,12 @@ module.exports = { ...@@ -168,13 +170,12 @@ module.exports = {
}); });
}, },
'POST /api/rule': (req, res) => { 'POST /api/rule': (req, res) => {
res res.status(200).send({
.status(200)
.send({
key: 71, key: 71,
disabled: true, disabled: true,
href: 'https://ant.design', href: 'https://ant.design',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png', avatar:
'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
name: '段勇', name: '段勇',
owner: 'Thomas', owner: 'Thomas',
desc: '院题质数下布进或会府速体快型前快。', desc: '院题质数下布进或会府速体快型前快。',
...@@ -186,9 +187,7 @@ module.exports = { ...@@ -186,9 +187,7 @@ module.exports = {
}); });
}, },
'PUT /api/rule': (req, res) => { 'PUT /api/rule': (req, res) => {
res res.status(200).send({
.status(200)
.send({
key: 94, key: 94,
disabled: true, disabled: true,
href: 'https://umijs.org/', 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 @@ ...@@ -98,9 +98,9 @@
"@ant-design/pro-utils": "^1.10.4", "@ant-design/pro-utils": "^1.10.4",
"@babel/polyfill": "7.4.3", "@babel/polyfill": "7.4.3",
"@babel/runtime": "^7.10.5", "@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/runtime": "0.0.15",
"@wisdom-utils/utils": "0.0.44", "@wisdom-utils/utils": "0.0.46",
"animate.css": "^4.1.1", "animate.css": "^4.1.1",
"antd": "^4.11.2", "antd": "^4.11.2",
"compression": "1.7.4", "compression": "1.7.4",
...@@ -114,7 +114,7 @@ ...@@ -114,7 +114,7 @@
"js-cookie": "^2.2.1", "js-cookie": "^2.2.1",
"kit_global_config": "^1.0.24", "kit_global_config": "^1.0.24",
"kit_logger": "^1.0.2", "kit_logger": "^1.0.2",
"kit_utils": "^1.3.10", "kit_utils": "^1.3.11",
"lodash": "4.17.11", "lodash": "4.17.11",
"minimist": "1.2.0", "minimist": "1.2.0",
"mqtt-client": "^1.0.11", "mqtt-client": "^1.0.11",
......
...@@ -60,6 +60,7 @@ const generateService = async ({ requestLibPath, schemaPath, mockFolder, ...rest ...@@ -60,6 +60,7 @@ const generateService = async ({ requestLibPath, schemaPath, mockFolder, ...rest
const requestImportStatement = getImportStatement(requestLibPath); const requestImportStatement = getImportStatement(requestLibPath);
const serviceGenerator = new serviceGenerators.ServiceGenerator({ const serviceGenerator = new serviceGenerators.ServiceGenerator({
namespace: 'API', namespace: 'API',
basePath: openAPI.servers[0].url,
requestImportStatement, requestImportStatement,
...rest, ...rest,
}, openAPI); }, openAPI);
......
const chalk = require('chalk'); 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; module.exports = Log;
const mockjs = require("mockjs"); const mockjs = require('mockjs');
const fs = require("fs"); const fs = require('fs');
const util = require("./util"); const path = require('path');
const path = require("path"); const util = require('./util');
const openAPIParserMock = require("./openAPIParserMock/index"); const openAPIParserMock = require('./openAPIParserMock/index');
const log = require("./log"); const log = require('./log');
mockjs.Random.extend({ mockjs.Random.extend({
country() { country() {
const data = [ const data = [
...@@ -56,7 +56,13 @@ mockjs.Random.extend({ ...@@ -56,7 +56,13 @@ mockjs.Random.extend({
return avatar[id]; return avatar[id];
}, },
group() { group() {
const data = ['体验技术部', '创新科技组', '前端 6 组', '区块链平台部', '服务技术部']; const data = [
'体验技术部',
'创新科技组',
'前端 6 组',
'区块链平台部',
'服务技术部',
];
const id = (Math.random() * data.length).toFixed(); const id = (Math.random() * data.length).toFixed();
return data[id]; return data[id];
}, },
...@@ -93,7 +99,7 @@ mockjs.Random.extend({ ...@@ -93,7 +99,7 @@ mockjs.Random.extend({
return href[id]; return href[id];
}, },
}); });
const genMockData = (example) => { const genMockData = example => {
if (!example) { if (!example) {
return {}; return {};
} }
...@@ -104,50 +110,61 @@ const genMockData = (example) => { ...@@ -104,50 +110,61 @@ const genMockData = (example) => {
return mockjs.mock(example); return mockjs.mock(example);
} }
return Object.keys(example) return Object.keys(example)
.map((name) => { .map(name => ({
return {
[name]: mockjs.mock(example[name]), [name]: mockjs.mock(example[name]),
}; }))
}) .reduce(
.reduce((pre, next) => { (pre, next) => ({
return {
...pre, ...pre,
...next, ...next,
}; }),
}, {}); {},
);
}; };
const genByTemp = ({ method, path, status, data, }) => { // eslint-disable-next-line no-shadow
if (!['get', 'put', 'post', 'delete', 'patch'].includes(method.toLocaleLowerCase())) { const genByTemp = ({ method, path, status, data }) => {
if (
!['get', 'put', 'post', 'delete', 'patch'].includes(
method.toLocaleLowerCase(),
)
) {
return ''; return '';
} }
return `'${method.toUpperCase()} ${path}': (req, res) => { return `'${method.toUpperCase()} ${path}': (req, res) => {
res.status(${status}).send(${data}); res.status(${status}).send(${data});
}`; }`;
}; };
const genMockFiles = (mockFunction) => { const genMockFiles = mockFunction =>
return util.prettierFile(` util.prettierFile(`
// @ts-ignore // @ts-ignore
//import { Request, Response } from 'express'; //import { Request, Response } from 'express';
module.exports = { module.exports = {
${mockFunction.join('\n,')} ${mockFunction.join('\n,')}
}`)[0]; }`)[0];
};
const mockGenerator = async ({ openAPI, mockFolder }) => { const mockGenerator = async ({ openAPI, mockFolder }) => {
// eslint-disable-next-line new-cap
const openAPParse = new openAPIParserMock(openAPI); const openAPParse = new openAPIParserMock(openAPI);
const docs = openAPParse.parser(); const docs = openAPParse.parser();
const pathList = Object.keys(docs.paths); const pathList = Object.keys(docs.paths);
const { paths } = docs; const { paths } = docs;
const mockActionsObj = {}; const mockActionsObj = {};
pathList.forEach((path) => { // eslint-disable-next-line no-shadow
pathList.forEach(path => {
const pathConfig = paths[path]; const pathConfig = paths[path];
Object.keys(pathConfig).forEach((method) => { Object.keys(pathConfig).forEach(method => {
const methodConfig = pathConfig[method]; const methodConfig = pathConfig[method];
if (methodConfig) { if (methodConfig) {
const conte = methodConfig && methodConfig.tags && methodConfig.tags.join('/') || const conte =
(methodConfig && methodConfig.tags && methodConfig.tags.join('/')) ||
path.replace('/', '').split('/')[1] || path.replace('/', '').split('/')[1] ||
methodConfig.operationId; 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]) { if (!mockActionsObj[conte]) {
mockActionsObj[conte] = []; mockActionsObj[conte] = [];
} }
...@@ -163,17 +180,21 @@ const mockGenerator = async ({ openAPI, mockFolder }) => { ...@@ -163,17 +180,21 @@ const mockGenerator = async ({ openAPI, mockFolder }) => {
} }
}); });
}); });
Object.keys(mockActionsObj).forEach((file) => { Object.keys(mockActionsObj).forEach(file => {
if (!file || file === 'undefined') { if (!file || file === 'undefined') {
return; 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', encoding: 'utf8',
}); },
);
}); });
log('✅ 生成 mock 文件成功'); log('✅ 生成 mock 文件成功');
}; };
module.exports = { module.exports = {
mockGenerator mockGenerator,
}; };
...@@ -24,9 +24,11 @@ const getDateByName = (name, parentsKey) => { ...@@ -24,9 +24,11 @@ const getDateByName = (name, parentsKey) => {
if (name.toLocaleLowerCase().endsWith('id')) { if (name.toLocaleLowerCase().endsWith('id')) {
return 'uuid'; return 'uuid';
} }
if (name.toLocaleLowerCase().endsWith('type') || if (
name.toLocaleLowerCase().endsWith('type') ||
name.toLocaleLowerCase().endsWith('key') || name.toLocaleLowerCase().endsWith('key') ||
['key'].includes(name)) { ['key'].includes(name)
) {
return 'id'; return 'id';
} }
if (name.toLocaleLowerCase().endsWith('label') || ['label'].includes(name)) { if (name.toLocaleLowerCase().endsWith('label') || ['label'].includes(name)) {
...@@ -59,33 +61,37 @@ const getDateByName = (name, parentsKey) => { ...@@ -59,33 +61,37 @@ const getDateByName = (name, parentsKey) => {
if (['country'].includes(name)) { if (['country'].includes(name)) {
return 'country'; return 'country';
} }
if (['url', 'imageUrl', 'href'].includes(name) || if (
['url', 'imageUrl', 'href'].includes(name) ||
name.toLocaleLowerCase().endsWith('url') || name.toLocaleLowerCase().endsWith('url') ||
name.toLocaleLowerCase().endsWith('urls') || name.toLocaleLowerCase().endsWith('urls') ||
name.toLocaleLowerCase().endsWith('image') || name.toLocaleLowerCase().endsWith('image') ||
name.toLocaleLowerCase().endsWith('link')) { name.toLocaleLowerCase().endsWith('link')
) {
return 'href'; return 'href';
} }
if (name.toLocaleLowerCase().endsWith('errorcode')) { if (name.toLocaleLowerCase().endsWith('errorcode')) {
return 'errorCode'; return 'errorCode';
} }
if (['type', 'status'].includes(name) || if (
['type', 'status'].includes(name) ||
name.toLocaleLowerCase().endsWith('status') || name.toLocaleLowerCase().endsWith('status') ||
name.toLocaleLowerCase().endsWith('type')) { name.toLocaleLowerCase().endsWith('type')
) {
return 'status'; return 'status';
} }
if (name.toLocaleLowerCase().endsWith('authority')) { if (name.toLocaleLowerCase().endsWith('authority')) {
return 'authority'; return 'authority';
} }
return 'csentence'; return 'csentence';
} };
function primitive(schemaParams, propsName) { function primitive(schemaParams, propsName) {
const schema = utils.objectify(schemaParams); const schema = utils.objectify(schemaParams);
console.log("schemaParams", propsName)
const { type, format } = schema; 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') { if (typeof schema.example === 'undefined') {
return value || `Unknown Type: ${schema.type}`; return value || `Unknown Type: ${schema.type}`;
} }
...@@ -102,19 +108,21 @@ class OpenAPIGeneratorMockJs { ...@@ -102,19 +108,21 @@ class OpenAPIGeneratorMockJs {
if (!type) { if (!type) {
if (properties) { if (properties) {
type = 'object'; type = 'object';
} } else if (items) {
else if (items) {
type = 'array'; type = 'array';
} } else {
else {
return null; return null;
} }
} }
if (type === 'object') { if (type === 'object') {
const props = utils.objectify(properties); const props = utils.objectify(properties);
const obj = {}; const obj = {};
// eslint-disable-next-line guard-for-in
for (const name in props) { for (const name in props) {
obj[name] = this.sampleFromSchema(props[name], [...(propsName || []), name]); obj[name] = this.sampleFromSchema(props[name], [
...(propsName || []),
name,
]);
} }
if (additionalProperties === true) { if (additionalProperties === true) {
obj.additionalProp1 = {}; obj.additionalProp1 = {};
...@@ -122,7 +130,10 @@ class OpenAPIGeneratorMockJs { ...@@ -122,7 +130,10 @@ class OpenAPIGeneratorMockJs {
} }
if (additionalProperties) { if (additionalProperties) {
const additionalProps = utils.objectify(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) { for (let i = 1; i < 4; i += 1) {
obj[`additionalProp${i}`] = additionalPropVal; obj[`additionalProp${i}`] = additionalPropVal;
} }
...@@ -131,11 +142,12 @@ class OpenAPIGeneratorMockJs { ...@@ -131,11 +142,12 @@ class OpenAPIGeneratorMockJs {
} }
if (type === 'array') { if (type === 'array') {
const item = this.sampleFromSchema(items, propsName); 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.enum) {
if (localSchema.default) if (localSchema.default) return localSchema.default;
return localSchema.default;
return utils.normalizeArray(localSchema.enum)[0]; return utils.normalizeArray(localSchema.enum)[0];
} }
if (type === 'file') { if (type === 'file') {
...@@ -144,23 +156,28 @@ class OpenAPIGeneratorMockJs { ...@@ -144,23 +156,28 @@ class OpenAPIGeneratorMockJs {
return primitive(localSchema, propsName); return primitive(localSchema, propsName);
}; };
this.parser = () => { this.parser = () => {
// eslint-disable-next-line no-shadow
const openAPI = { const openAPI = {
...this.openAPI, ...this.openAPI,
}; };
// eslint-disable-next-line guard-for-in
for (const path in openAPI.paths) { for (const path in openAPI.paths) {
// eslint-disable-next-line guard-for-in
for (const method in openAPI.paths[path]) { for (const method in openAPI.paths[path]) {
const api = openAPI.paths[path][method]; const api = openAPI.paths[path][method];
// eslint-disable-next-line guard-for-in
for (const code in api.responses) { for (const code in api.responses) {
const response = api.responses[code]; const response = api.responses[code];
const schema = response.content && const schema =
response.content &&
response.content['application/json'] && response.content['application/json'] &&
utils.inferSchema(response.content['application/json']); utils.inferSchema(response.content['application/json']);
if (schema) { if (schema) {
response.example = schema ? this.sampleFromSchema(schema) : null; response.example = schema ? this.sampleFromSchema(schema) : null;
} }
} }
if (!api.parameters) // eslint-disable-next-line no-continue
continue; if (!api.parameters) continue;
for (const parameter of api.parameters) { for (const parameter of api.parameters) {
const schema = utils.inferSchema(parameter); const schema = utils.inferSchema(parameter);
parameter.example = schema ? this.sampleFromSchema(schema) : null; parameter.example = schema ? this.sampleFromSchema(schema) : null;
......
...@@ -27,4 +27,4 @@ module.exports = { ...@@ -27,4 +27,4 @@ module.exports = {
number_float: '@float(60, 100, 3, 5)', number_float: '@float(60, 100, 3, 5)',
integer: '@integer(60, 100)', integer: '@integer(60, 100)',
boolean: '@boolean', boolean: '@boolean',
} };
\ No newline at end of file
...@@ -3,8 +3,7 @@ function isObject(obj) { ...@@ -3,8 +3,7 @@ function isObject(obj) {
} }
function objectify(thing) { function objectify(thing) {
if (!isObject(thing)) if (!isObject(thing)) return {};
return {};
return thing; return thing;
} }
...@@ -20,8 +19,7 @@ function get(entity, path) { ...@@ -20,8 +19,7 @@ function get(entity, path) {
} }
function normalizeArray(arr) { function normalizeArray(arr) {
if (Array.isArray(arr)) if (Array.isArray(arr)) return arr;
return arr;
return [arr]; return [arr];
} }
...@@ -48,5 +46,5 @@ module.exports = { ...@@ -48,5 +46,5 @@ module.exports = {
get, get,
normalizeArray, normalizeArray,
isFunc, isFunc,
inferSchema inferSchema,
} };
\ No newline at end of file
...@@ -21,9 +21,9 @@ function createMiddleware(config) { ...@@ -21,9 +21,9 @@ function createMiddleware(config) {
if (serversFolder && !existsSync(serversFolder)) { if (serversFolder && !existsSync(serversFolder)) {
mkdirSync(serversFolder); mkdirSync(serversFolder);
} }
// pageConfig.name.split('/').pop(),
await generateService({ await generateService({
projectName: '', projectName: '',
//pageConfig.name.split('/').pop(),
...openAPIConfig, ...openAPIConfig,
serversPath: serversFolder, serversPath: serversFolder,
mockFolder, mockFolder,
......
/* eslint-disable */
const fs = require('fs'); const fs = require('fs');
const glob = require('glob'); const glob = require('glob');
const rimraf = require('rimraf'); const rimraf = require('rimraf');
const nunjucks = require("nunjucks"); const nunjucks = require('nunjucks');
const path = require('path'); const path = require('path');
const lodash = require('lodash'); const lodash = require('lodash');
const reservedWords = require('reserved-words'); const reservedWords = require('reserved-words');
...@@ -159,7 +160,7 @@ class ServiceGenerator { ...@@ -159,7 +160,7 @@ class ServiceGenerator {
}; };
this.openAPIData = openAPIData; this.openAPIData = openAPIData;
const { info } = openAPIData; const { info } = openAPIData;
const basePath = ''; const basePath = config.basePath || '';
this.version = info.version; this.version = info.version;
Object.keys(openAPIData.paths || {}).forEach((p) => { Object.keys(openAPIData.paths || {}).forEach((p) => {
const pathItem = openAPIData.paths[p]; const pathItem = openAPIData.paths[p];
...@@ -182,7 +183,7 @@ class ServiceGenerator { ...@@ -182,7 +183,7 @@ class ServiceGenerator {
}); });
} }
genFile() { genFile() {
const basePath = this.config.serversPath || './src/service'; const basePath = this.config.serversPath || './src/api/generateAPI';
try { try {
const finalPath = path.join(basePath, this.config.projectName); const finalPath = path.join(basePath, this.config.projectName);
this.finalPath = finalPath; this.finalPath = finalPath;
...@@ -325,6 +326,7 @@ class ServiceGenerator { ...@@ -325,6 +326,7 @@ class ServiceGenerator {
// prefix 变量 // prefix 变量
return `$\{${prefix}}${formattedPath}`; return `$\{${prefix}}${formattedPath}`;
}; };
return { return {
...newApi, ...newApi,
functionName, functionName,
...@@ -625,4 +627,4 @@ module.exports = { ...@@ -625,4 +627,4 @@ module.exports = {
getPath, getPath,
getGenInfo, getGenInfo,
ServiceGenerator ServiceGenerator
} };
\ No newline at end of file
...@@ -13,18 +13,11 @@ import 'sanitize.css/sanitize.css'; ...@@ -13,18 +13,11 @@ import 'sanitize.css/sanitize.css';
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import { import { Button, message, notification } from 'antd';
Button,
message,
notification,
} from 'antd';
import { ConnectedRouter } from 'connected-react-router/immutable'; import { ConnectedRouter } from 'connected-react-router/immutable';
import Immutable from 'immutable'; import Immutable from 'immutable';
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
import { import { params, Storeage } from 'kit_utils';
params,
Storeage,
} from 'kit_utils';
import { Provider } from 'react-redux'; import { Provider } from 'react-redux';
import { useIntl } from '@/locales/localeExports'; import { useIntl } from '@/locales/localeExports';
...@@ -42,15 +35,13 @@ import { actionCreators } from './containers/App/store'; ...@@ -42,15 +35,13 @@ import { actionCreators } from './containers/App/store';
import { LocaleContainer } from './locales/locale'; import { LocaleContainer } from './locales/locale';
import { initMicroApps } from './micro'; import { initMicroApps } from './micro';
import Login from './pages/user/login/login'; import Login from './pages/user/login/login';
import { import { getToken, isString } from './utils/utils';
getToken,
isString,
} from './utils/utils';
const isHttps = document.location.protocol === 'https:'; const isHttps = document.location.protocol === 'https:';
const { pwa } = defaultSettings; const { pwa } = defaultSettings;
// eslint-disable-next-line no-restricted-globals // eslint-disable-next-line no-restricted-globals
const namespace = `__PANDA_STORE__${location.hostname}`; const namespace = `__PANDA_STORE__${location.hostname}`;
debugger
window.createStoreage = new Storeage(namespace); window.createStoreage = new Storeage(namespace);
// eslint-disable-next-line no-underscore-dangle // eslint-disable-next-line no-underscore-dangle
const initialState = Immutable.Map(); const initialState = Immutable.Map();
...@@ -83,6 +74,8 @@ const initLocale = () => { ...@@ -83,6 +74,8 @@ const initLocale = () => {
}; };
const initGlobalConfig = () => { const initGlobalConfig = () => {
// eslint-disable-next-line no-debugger
debugger
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
let config = createStoreage.get('globalConfig') || {}; let config = createStoreage.get('globalConfig') || {};
store.dispatch(actionCreators.updateComplexConfig({})); store.dispatch(actionCreators.updateComplexConfig({}));
...@@ -188,15 +181,7 @@ window.share && ...@@ -188,15 +181,7 @@ window.share &&
window.share.event.on('triggerMicro', () => { window.share.event.on('triggerMicro', () => {
initMicroApps(loader, store); 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) { if (pwa) {
// const appPWA = window.i18n.getI18n('app'); // const appPWA = window.i18n.getI18n('app');
......
...@@ -163,10 +163,13 @@ export function updateMicroMounted(data) { ...@@ -163,10 +163,13 @@ export function updateMicroMounted(data) {
} }
export function logout(data) { export function logout(data) {
// eslint-disable-next-line no-undef
createStoreage.remove('PANDA_STORE'); createStoreage.remove('PANDA_STORE');
if (window.globalConfig) {
Cookies.set(window.globalConfig.client, '', { Cookies.set(window.globalConfig.client, '', {
path: '/', path: '/',
}); });
}
Cookies.set('token', '', { Cookies.set('token', '', {
path: '/', path: '/',
...@@ -183,13 +186,13 @@ export function logout(data) { ...@@ -183,13 +186,13 @@ export function logout(data) {
path: '/', path: '/',
}); });
localStorage.removeItem('access_token'); localStorage.removeItem('access_token');
// eslint-disable-next-line no-undef,no-restricted-globals
createStoreage.remove(`__PANDA_STORE__${location.hostname}`); createStoreage.remove(`__PANDA_STORE__${location.hostname}`);
return { return {
type: LOGINOUT, type: LOGINOUT,
data: { data: {
currentMenuIndex: 0, currentMenuIndex: 0,
// config: {}, complexConfig: {},
complexConfig: {} },
} };
}
} }
...@@ -198,7 +198,7 @@ const appReducer = (state = initialState, action) => { ...@@ -198,7 +198,7 @@ const appReducer = (state = initialState, action) => {
return state.merge({ return state.merge({
complexConfig: action.data.complexConfig, complexConfig: action.data.complexConfig,
currentMenuIndex: action.data.currentMenuIndex, currentMenuIndex: action.data.currentMenuIndex,
}) });
default: default:
return state; return state;
} }
......
...@@ -50,7 +50,7 @@ export const initMicroApps = (loader, store) => { ...@@ -50,7 +50,7 @@ export const initMicroApps = (loader, store) => {
item.activeRule = genActiveRule(`/civbase/${item.PackageName}`); item.activeRule = genActiveRule(`/civbase/${item.PackageName}`);
item.props = JSON.parse(item.DefaultSetting); item.props = JSON.parse(item.DefaultSetting);
return item; return item;
}) }) || micorConfig.prod
: micorConfig.prod; : micorConfig.prod;
registerMicroApps( registerMicroApps(
......
...@@ -9,7 +9,9 @@ export default () => { ...@@ -9,7 +9,9 @@ export default () => {
switch(loginTemplate) { switch(loginTemplate) {
case '新春 - 智联.html': case '新春 - 智联.html':
return <NewYear/> return <NewYear/>
default: case 'Dark.html':
return <BaseLogin/> return <BaseLogin/>
default:
return <></>;
} }
}; };
import 'kit_utils/lib/format'; import 'kit_utils/lib/format';
import React, { import React, { forwardRef, useEffect, useRef, useState } from 'react';
forwardRef,
useEffect,
useRef,
useState,
} from 'react';
import { import { Alert, Checkbox, Form, Modal, Popover } from 'antd';
Alert,
Checkbox,
Form,
Modal,
Popover,
} from 'antd';
import classNames from 'classnames'; import classNames from 'classnames';
import { encode } from 'js-base64'; import { encode } from 'js-base64';
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
import { dom } from 'kit_utils'; import { dom } from 'kit_utils';
import QRCode from 'qrcode.react'; import QRCode from 'qrcode.react';
import { import { Helmet, HelmetProvider } from 'react-helmet-async';
Helmet,
HelmetProvider,
} from 'react-helmet-async';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom'; import { withRouter } from 'react-router-dom';
import { import { LOGIN_DISPLAY, LOGIN_WAY } from '@/constants';
LOGIN_DISPLAY,
LOGIN_WAY,
} from '@/constants';
import { actionCreators } from '@/containers/App/store'; import { actionCreators } from '@/containers/App/store';
import { useIntl } from '@/locales/localeExports'; import { useIntl } from '@/locales/localeExports';
...@@ -556,7 +539,7 @@ const Login = forwardRef((props, _ref) => { ...@@ -556,7 +539,7 @@ const Login = forwardRef((props, _ref) => {
> >
<img <img
role="logo" role="logo"
src={props.global.transformDevAssetsBaseURL(props.global.logo)} src={props.global && props.global.transformDevAssetsBaseURL && props.global.transformDevAssetsBaseURL(props.global.logo)}
/> />
<div <div
className={classNames( className={classNames(
......
...@@ -35,15 +35,29 @@ export const dyRoutes = routes => { ...@@ -35,15 +35,29 @@ export const dyRoutes = routes => {
process.env.NODE_ENV === 'development' && { process.env.NODE_ENV === 'development' && {
path: '/openapi', path: '/openapi',
exact: true, 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', 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', 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