Unverified Commit ac07f7c0 authored by zhu-mingye's avatar zhu-mingye Committed by GitHub

[Optimization] optimization dinky-web module (#1676)

* Optimize web module * modify version import * modify routes
parent 753b229a
# Declare files that will always have LF line endings on checkout.
*.java text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.xml text eol=lf
*.sh eol=lf
*.py eol=lf
*.md text eol=lf
*.mdx text eol=lf
*.ts text eol=lf
*.tsx text eol=lf
*.js text eol=lf
*.json text eol=lf
*.less text eol=lf
*.txt text eol=lf
*.jpg -text
\ No newline at end of file
......@@ -42,15 +42,15 @@ export default [
{
path: '/',
redirect: '/dataStudio',
redirect: '/datastudio',
},
{
path: '/dataStudio',
name: 'dataStudio',
path: '/datastudio',
name: 'datastudio',
icon: 'consoleSql',
footerRender: false,
// component: './DataStudio',
component: './DataStudio',
},
{
path: '/devops',
......@@ -89,7 +89,7 @@ export default [
routes: [
{
path: '/registration',
redirect: '/registration/cluster/clusterInstance',
redirect: '/registration/cluster/instance',
},
{
path: '/registration/cluster',
......@@ -97,13 +97,13 @@ export default [
icon: 'cluster',
routes: [
{
path: '/registration/cluster/clusterInstance',
name: 'clusterInstance',
path: '/registration/cluster/instance',
name: 'cluster-instance',
// component: './RegistrationCenter/ClusterManage/Cluster',
},
{
path: '/registration/cluster/clusterConfiguration',
name: 'clusterConfiguration',
path: '/registration/cluster/config',
name: 'cluster-config',
// component: './RegistrationCenter/ClusterManage/ClusterConfiguration',
},
],
......@@ -126,13 +126,13 @@ export default [
icon: 'alert',
routes: [
{
path: '/registration/alert/alertInstance',
name: 'alertInstance',
path: '/registration/alert/instance',
name: 'instance',
// component: './RegistrationCenter/AlertManage/AlertInstance',
},
{
path: '/registration/alert/alertGroup',
name: 'alertGroup',
path: '/registration/alert/group',
name: 'group',
// component: './RegistrationCenter/AlertManage/AlertGroup',
},
],
......@@ -152,36 +152,36 @@ export default [
],
},
{
name: 'authenticationCenter',
name: 'authentication',
icon: 'SafetyCertificateOutlined',
path: '/authenticationCenter',
path: '/authentication',
// access: "canAdmin",
routes: [
{
path: '/authenticationCenter',
redirect: '/authenticationCenter/userManager',
path: '/authentication',
redirect: '/authentication/usermanager',
},
{
path: '/authenticationCenter/userManager',
name: 'userManager',
path: '/authentication/usermanager',
name: 'usermanager',
icon: 'UserOutlined',
// component: './AuthenticationCenter/UserManager',
},
{
path: '/authenticationCenter/roleManager',
name: 'roleManager',
path: '/authentication/role',
name: 'role',
icon: 'TeamOutlined',
// component: './AuthenticationCenter/RoleManager',
},
{
path: '/authenticationCenter/namespaceManager',
name: 'namespaceManager',
path: '/authentication/namespace',
name: 'namespace',
icon: 'BulbOutlined',
// component: './AuthenticationCenter/NamespaceManager',
},
{
path: '/authenticationCenter/tenantManager',
name: 'tenantManager',
path: '/authentication/tenant',
name: 'tenant',
icon: 'SecurityScanOutlined',
// component: './AuthenticationCenter/TenantManager',
},
......@@ -191,38 +191,50 @@ export default [
{
name: 'settings',
icon: 'setting',
path: '/settingCenter',
path: '/settings',
routes: [
{
path: '/settingCenter',
redirect: '/settingCenter/flinkSettings',
path: '/settings',
redirect: '/settings/flinksetting',
},
{
path: '/settingCenter/flinkSettings',
name: 'flinkConfig',
path: '/settings/flinksetting',
name: 'flinksetting',
icon: 'setting',
// component: './SettingCenter/FlinkSettings',
},
{
path: '/settingCenter/udfTemplate',
name: 'udfTemplate',
path: '/settings/udf',
name: 'udf',
icon: 'setting',
// component: './SettingCenter/UDFTemplate',
},
{
path: '/settingCenter/systemInfo',
name: 'systemInfo',
path: '/settings/system',
name: 'system',
icon: 'desktop',
// component: './SettingCenter/SystemInfo',
},
{
path: '/settingCenter/processList',
name: 'processList',
path: '/settings/process',
name: 'process',
icon: 'desktop',
// component: './SettingCenter/ProcessList',
},
{
path: '/settings/services',
name: 'services',
icon: 'MacCommandOutlined',
// component: './SettingCenter/Service',
},
],
},
{
path: '/metrics',
name: 'metrics',
icon: 'AreaChartOutlined',
// component: './Metrics',
},
{
path: '/about',
name: 'about',
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Request, Response } from 'express';
import moment from 'moment';
import { parse } from 'url';
// mock tableListDataSource
const genList = (current: number, pageSize: number) => {
const tableListDataSource: API.RuleListItem[] = [];
for (let i = 0; i < pageSize; i += 1) {
const index = (current - 1) * 10 + i;
tableListDataSource.push({
key: index,
disabled: i % 6 === 0,
href: 'https://ant.design',
avatar: [
'https://gw.alipayobjects.com/zos/rmsportal/eeHMaZBwmTvLdIwMfBpg.png',
'https://gw.alipayobjects.com/zos/rmsportal/udxAbMEhpwthVVcjLXik.png',
][i % 2],
name: `TradeCode ${index}`,
owner: '曲丽丽',
desc: '这是一段描述',
callNo: Math.floor(Math.random() * 1000),
status: Math.floor(Math.random() * 10) % 4,
updatedAt: moment().format('YYYY-MM-DD'),
createdAt: moment().format('YYYY-MM-DD'),
progress: Math.ceil(Math.random() * 100),
});
}
tableListDataSource.reverse();
return tableListDataSource;
};
let tableListDataSource = genList(1, 100);
function getRule(req: Request, res: Response, u: string) {
let realUrl = u;
if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
realUrl = req.url;
}
const { current = 1, pageSize = 10 } = req.query;
const params = parse(realUrl, true).query as unknown as API.PageParams &
API.RuleListItem & {
sorter: any;
filter: any;
};
let dataSource = [...tableListDataSource].slice(
((current as number) - 1) * (pageSize as number),
(current as number) * (pageSize as number),
);
if (params.sorter) {
const sorter = JSON.parse(params.sorter);
dataSource = dataSource.sort((prev, next) => {
let sortNumber = 0;
(Object.keys(sorter) as Array<keyof API.RuleListItem>).forEach((key) => {
let nextSort = next?.[key] as number;
let preSort = prev?.[key] as number;
if (sorter[key] === 'descend') {
if (preSort - nextSort > 0) {
sortNumber += -1;
} else {
sortNumber += 1;
}
return;
}
if (preSort - nextSort > 0) {
sortNumber += 1;
} else {
sortNumber += -1;
}
});
return sortNumber;
});
}
if (params.filter) {
const filter = JSON.parse(params.filter as any) as {
[key: string]: string[];
};
if (Object.keys(filter).length > 0) {
dataSource = dataSource.filter((item) => {
return (Object.keys(filter) as Array<keyof API.RuleListItem>).some((key) => {
if (!filter[key]) {
return true;
}
if (filter[key].includes(`${item[key]}`)) {
return true;
}
return false;
});
});
}
}
if (params.name) {
dataSource = dataSource.filter((data) => data?.name?.includes(params.name || ''));
}
const result = {
data: dataSource,
total: tableListDataSource.length,
success: true,
pageSize,
current: parseInt(`${params.current}`, 10) || 1,
};
return res.json(result);
}
function postRule(req: Request, res: Response, u: string, b: Request) {
let realUrl = u;
if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
realUrl = req.url;
}
const body = (b && b.body) || req.body;
const { method, name, desc, key } = body;
switch (method) {
/* eslint no-case-declarations:0 */
case 'delete':
tableListDataSource = tableListDataSource.filter((item) => key.indexOf(item.key) === -1);
break;
case 'post':
(() => {
const i = Math.ceil(Math.random() * 10000);
const newRule: API.RuleListItem = {
key: tableListDataSource.length,
href: 'https://ant.design',
avatar: [
'https://gw.alipayobjects.com/zos/rmsportal/eeHMaZBwmTvLdIwMfBpg.png',
'https://gw.alipayobjects.com/zos/rmsportal/udxAbMEhpwthVVcjLXik.png',
][i % 2],
name,
owner: '曲丽丽',
desc,
callNo: Math.floor(Math.random() * 1000),
status: Math.floor(Math.random() * 10) % 2,
updatedAt: moment().format('YYYY-MM-DD'),
createdAt: moment().format('YYYY-MM-DD'),
progress: Math.ceil(Math.random() * 100),
};
tableListDataSource.unshift(newRule);
return res.json(newRule);
})();
return;
case 'update':
(() => {
let newRule = {};
tableListDataSource = tableListDataSource.map((item) => {
if (item.key === key) {
newRule = { ...item, desc, name };
return { ...item, desc, name };
}
return item;
});
return res.json(newRule);
})();
return;
default:
break;
}
const result = {
list: tableListDataSource,
pagination: {
total: tableListDataSource.length,
},
};
res.json(result);
}
export default {
'GET /api/rule': getRule,
'POST /api/rule': postRule,
};
......@@ -47,6 +47,8 @@
"dependencies": {
"@ant-design/icons": "^5.0.1",
"@ant-design/pro-components": "^2.3.52",
"@ant-design/pro-layout": "^7.8.2",
"@ant-design/pro-table": "^2.5.6",
"@ant-design/use-emotion-css": "1.0.4",
"@umijs/route-utils": "^4.0.1",
"antd": "^5.0.0",
......@@ -60,8 +62,13 @@
"react": "^18.0.0",
"react-dev-inspector": "^1.8.1",
"react-dom": "^18.0.0",
"react-draggable": "^4.4.5",
"react-helmet-async": "^1.3.0",
"screenfull": "^6.0.2"
"screenfull": "^6.0.2",
"xterm": "^5.1.0",
"xterm-addon-attach": "^0.8.0",
"xterm-addon-fit": "^0.7.0",
"xterm-addon-web-links": "^0.8.0"
},
"devDependencies": {
"@ant-design/pro-cli": "^2.1.0",
......
......@@ -17,16 +17,15 @@
*
*/
import { PasswordItem } from '@/types/User/data';
import { l } from '@/utils/intl';
import { Button, Form, Input, Modal } from 'antd';
import React, { useState } from 'react';
export type PasswordFormProps = {
onCancel: (flag?: boolean) => void;
onSubmit: (values: Partial<PasswordItem>) => void;
onSubmit: (values: Partial<UserBaseInfo.ChangePasswordParams>) => void;
modalVisible: boolean;
values: Partial<PasswordItem>;
values: Partial<UserBaseInfo.ChangePasswordParams>;
};
const formLayout = {
......@@ -36,7 +35,7 @@ const formLayout = {
const PasswordForm: React.FC<PasswordFormProps> = (props) => {
const [form] = Form.useForm();
const [formVals, setFormVals] = useState<Partial<PasswordItem>>({
const [formVals, setFormVals] = useState<Partial<UserBaseInfo.ChangePasswordParams>>({
username: props.values.username,
});
......
......@@ -37,7 +37,7 @@ const Name = () => {
const nameClassName = useEmotionCss(({ token }) => {
return {
width: '70px',
width: 'auto',
height: '48px',
overflow: 'hidden',
lineHeight: '48px',
......
......@@ -15,30 +15,48 @@
* limitations under the License.
*/
import { VERSION } from '@/components/Version/Version';
import { l } from '@/utils/intl';
import { FullscreenOutlined, GlobalOutlined } from '@ant-design/icons';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { SelectLang, useModel } from '@umijs/max';
import { Space, Tooltip } from 'antd';
import React, { useState } from 'react';
import {chooseTenantSubmit} from '@/services/api';
import { VERSION } from '@/services/constants';
import {parseJsonStr, setTenantStorageAndCookie} from '@/services/function';
import {l} from '@/utils/intl';
import {
CreditCardOutlined,
FullscreenExitOutlined,
FullscreenOutlined,
GlobalOutlined
} from '@ant-design/icons';
import {ActionType} from '@ant-design/pro-components';
import {useEmotionCss} from '@ant-design/use-emotion-css';
import {SelectLang, useModel} from '@umijs/max';
import {Modal, notification, Select, Space, Tooltip} from 'antd';
import {OptionType} from 'dayjs';
import React, {useRef, useState} from 'react';
import screenfull from 'screenfull';
import Avatar from './AvatarDropdown';
export type SiderTheme = 'light' | 'dark';
const GlobalHeaderRight: React.FC = () => {
const [fullScreen, setFullScreen] = useState(false);
const actionRef = useRef<ActionType>();
const [fullScreen, setFullScreen] = useState(true);
const actionClassName = useEmotionCss(({ token }) => {
const {initialState} = useModel('@@initialState');
const {currentUser} = initialState || {};
if (!initialState || !initialState.settings) {
return null;
}
const actionClassName = useEmotionCss(({token}) => {
return {
display: 'flex',
float: 'right',
justifyContent: 'center',
alignItems: 'center',
height: '48px',
marginLeft: 'auto',
overflow: 'hidden',
cursor: 'pointer',
padding: '0 12px',
padding: '0 9px',
color: '#fff',
borderRadius: token.borderRadius,
'&:hover': {
......@@ -47,7 +65,7 @@ const GlobalHeaderRight: React.FC = () => {
};
});
const fullScreenClassName = useEmotionCss(({ token }) => {
const fullScreenClassName = useEmotionCss(({token}) => {
return {
display: 'flex',
float: 'right',
......@@ -64,11 +82,24 @@ const GlobalHeaderRight: React.FC = () => {
};
});
const { initialState } = useModel('@@initialState');
if (!initialState || !initialState.settings) {
return null;
}
const tenantHandleChange = (option: OptionType) => {
const result = parseJsonStr(option as string);
const tenantId = result.value;
Modal.confirm({
title: l('menu.account.checkTenant'),
content: l('menu.account.checkTenantConfirm', '', {tenantCode: result.children}),
okText: l('button.confirm'),
cancelText: l('button.cancel'),
onOk: async () => {
const result = await chooseTenantSubmit({tenantId: tenantId});
setTenantStorageAndCookie(tenantId);
result.code == 0 ? notification.success({message: result.msg,}) : notification.error({message: result.msg});
actionRef.current?.reload();
},
});
};
const screenFull = () => {
setFullScreen(screenfull.isFullscreen);
......@@ -77,21 +108,59 @@ const GlobalHeaderRight: React.FC = () => {
}
};
const genTenantListForm = () => {
const tenants: any[] = [];
currentUser?.tenantList?.forEach((item) => {
tenants.push(
<Select.Option key={item.id} value={item.id}>
{item.tenantCode}
</Select.Option>,
);
});
return tenants;
};
return (
<>
<Tooltip
placement="bottom"
title={<span>{fullScreen ? l('global.fullScreen') : l('global.fullScreen.exit')}</span>}
>
<FullscreenOutlined
style={{ color: 'white' }}
className={fullScreenClassName}
onClick={screenFull}
/>
{fullScreen ?
<FullscreenOutlined
style={{color: 'white'}}
className={fullScreenClassName}
onClick={screenFull}
/> :
<FullscreenExitOutlined
style={{color: 'white'}}
className={fullScreenClassName}
onClick={screenFull}
/>
}
</Tooltip>
<Avatar menu={true}/>
{
<>
<span className={actionClassName}>{l('menu.tenants')}</span>
<Select className={actionClassName}
style={{width: '18vh'}}
defaultValue={currentUser?.currentTenant?.tenantCode?.toString() || ''}
onChange={(value, option) => {
tenantHandleChange(option as OptionType);
}}
>
{genTenantListForm()}
</Select>
</>
}
<Tooltip
placement="bottom"
title={<span>{l('menu.version', '', {version: VERSION})}</span>}
>
<Space className={actionClassName}>{l('menu.version', '', {version: VERSION})}</Space>
</Tooltip>
<Avatar menu={true} />
<SelectLang icon={<GlobalOutlined />} className={actionClassName} />
<Space className={actionClassName}>{l('menu.version', '', { version: VERSION })}</Space>
<SelectLang icon={<GlobalOutlined/>} className={actionClassName}/>
</>
);
};
......
......@@ -31,34 +31,37 @@ export default {
'menu.account.logout': 'Logout',
'menu.account.changePassword': 'Change Password',
'menu.account.checkTenant': 'Check Tenant',
'menu.tenants': 'Tenant: ',
'menu.account.checkTenantConfirm': 'Are you sure to switch tenant [ {tenantCode} ] ?',
'menu.dataStudio': 'Data Studio',
'menu.datastudio': 'Data Studio',
'menu.devops': 'Devops',
'menu.job': 'Job Instance',
'menu.datacenter': 'Meta Data Center',
'menu.datacenter.metadata': 'Meta Data',
'menu.registration': 'Registration Center',
'menu.registration.cluster': 'Cluster Management',
'menu.registration.cluster.clusterInstance': 'Flink Instance',
'menu.registration.cluster.clusterConfiguration': 'Cluster Config',
'menu.registration.cluster.cluster-instance': 'Flink Instance',
'menu.registration.cluster.cluster-config': 'Cluster Config',
'menu.registration.jar': 'Jar Management',
'menu.registration.database': 'Data Source Management',
'menu.registration.alert': 'Alarm Management',
'menu.registration.alert.alertInstance': 'Alarm Instance Management',
'menu.registration.alert.alertGroup': 'Alarm Group Management',
'menu.registration.alert.instance': 'Alarm Instance Management',
'menu.registration.alert.group': 'Alarm Group Management',
'menu.registration.document': 'Document Management',
'menu.registration.fragment': 'Global Variable Management',
'menu.authenticationCenter': 'Authentication Center',
'menu.authenticationCenter.userManager': 'User Management',
'menu.authenticationCenter.namespaceManager': 'NameSpace Management',
'menu.authenticationCenter.roleManager': 'Role Management',
'menu.authenticationCenter.tenantManager': 'Tenant Management',
'menu.authentication': 'Authentication Center',
'menu.authentication.usermanager': 'User Management',
'menu.authentication.role': 'Role Management',
'menu.authentication.namespace': 'NameSpace Management',
'menu.authentication.tenant': 'Tenant Management',
'menu.settings': 'Setting Center',
'menu.settings.flinkConfig': 'Flink Settings',
'menu.settings.udfTemplate': 'UDF Template Settings',
'menu.settings.systemInfo': 'System Info',
'menu.settings.processList': 'Process List',
'menu.settings.flinksetting': 'Flink Settings',
'menu.settings.udf': 'UDF Template Settings',
'menu.settings.system': 'System Info',
'menu.settings.process': 'Process List',
'menu.settings.services': 'Servers List',
'menu.metrics': 'Dashboard',
'menu.about': 'About',
'menu.version': 'Version: {version}',
};
......@@ -24,7 +24,7 @@ export default {
'pages.login.chooseTenant': 'Please Choose Tenant',
'pages.login.chooseTenantFailed': 'Tenant selection failed, please check. . . ',
'pages.login.chooseTenantSuccess':
'{msg}, we are about to use [{tenantCode}] to enter the system, please wait...',
'{msg}, Use [ {tenantCode} ] to enter the system, loading. . .',
'pages.login.password.placeholder': 'Password',
'pages.login.password.required': 'Please input your password!',
'pages.login.rememberMe': 'Remember me',
......
......@@ -31,34 +31,37 @@ export default {
'menu.account.logout': '退出登录',
'menu.account.changePassword': '修改密码',
'menu.account.checkTenant': '切换租户',
'menu.tenants': '租户:',
'menu.account.checkTenantConfirm': '你确定切换租户【{tenantCode}】吗?',
'menu.dataStudio': '数据开发',
'menu.datastudio': '数据开发',
'menu.devops': '运维中心',
'menu.job': '作业实例',
'menu.datacenter': '元数据中心',
'menu.datacenter.metadata': '元数据',
'menu.registration': '注册中心',
'menu.registration.cluster': '集群管理',
'menu.registration.cluster.clusterInstance': 'Flink 实例管理',
'menu.registration.cluster.clusterConfiguration': '集群配置管理',
'menu.registration.cluster.cluster-instance': 'Flink 实例管理',
'menu.registration.cluster.cluster-config': '集群配置管理',
'menu.registration.jar': 'Jar 管理',
'menu.registration.database': '数据源管理',
'menu.registration.alert': '报警管理',
'menu.registration.alert.alertInstance': '报警实例管理',
'menu.registration.alert.alertGroup': '报警组管理',
'menu.registration.alert.instance': '报警实例管理',
'menu.registration.alert.group': '报警组管理',
'menu.registration.document': '文档管理',
'menu.registration.fragment': '全局变量管理',
'menu.authenticationCenter': '认证中心',
'menu.authenticationCenter.userManager': '用户管理',
'menu.authenticationCenter.namespaceManager': '命名空间管理',
'menu.authenticationCenter.roleManager': '角色管理',
'menu.authenticationCenter.tenantManager': '租户管理',
'menu.authentication': '认证中心',
'menu.authentication.usermanager': '用户管理',
'menu.authentication.role': '角色管理',
'menu.authentication.namespace': '命名空间管理',
'menu.authentication.tenant': '租户管理',
'menu.settings': '配置中心',
'menu.settings.flinkConfig': 'Flink 配置',
'menu.settings.udfTemplate': 'UDF 模板配置',
'menu.settings.systemInfo': '系统信息',
'menu.settings.processList': '进程列表',
'menu.settings.flinksetting': 'Flink 配置',
'menu.settings.udf': 'UDF 模板配置',
'menu.settings.system': '系统信息',
'menu.settings.process': '进程列表',
'menu.settings.services': '服务器列表',
'menu.metrics': '监控',
'menu.about': '关于',
'menu.version': '版本:{version}',
};
......@@ -23,7 +23,7 @@ export default {
'pages.login.username.required': '用户名是必填项!',
'pages.login.chooseTenant': '请选择租户',
'pages.login.chooseTenantFailed': '租户选择失败,请检查。。。',
'pages.login.chooseTenantSuccess': '{msg},即将使用【 {tenantCode} 】进入系统,请稍后。。。',
'pages.login.chooseTenantSuccess': '{msg},使用【 {tenantCode} 】进入系统,加载中。。。',
'pages.login.password.placeholder': '密码',
'pages.login.password.required': '密码是必填项!',
'pages.login.rememberMe': '自动登录',
......
......@@ -15,7 +15,7 @@
* limitations under the License.
*/
import { VERSION } from '@/components/Version/Version';
import { VERSION } from '@/services/constants';
import { l } from '@/utils/intl';
import { HeartOutlined, LinkOutlined, SmileOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Card } from 'antd';
const DataStudio = (props: any) => {
return (
<div style={{ margin: '-24px' }}>
<Card bordered={false} size="small" id="studio_card" style={{ marginBottom: 0 }}></Card>
</div>
);
};
export default DataStudio;
......@@ -18,13 +18,13 @@
import Footer from '@/components/Footer';
import { chooseTenantSubmit, login } from '@/services/api';
import { setTenantStorageAndCookie } from '@/services/function';
import { l } from '@/utils/intl';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { CheckCard, LoginForm, ProFormCheckbox, ProFormText } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { Helmet, history, SelectLang, useModel } from '@umijs/max';
import { Button, message, Modal } from 'antd';
import cookies from 'js-cookie';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';
import Settings from '../../../../config/defaultSettings';
......@@ -143,7 +143,7 @@ const Login: React.FC = () => {
handleTenantVisible(true);
} else {
setTenantIdParams(tenantList[0].id as number);
setTenantCookie(tenantList[0].id as number);
setTenantStorageAndCookie(tenantList[0].id as number);
const chooseTenantResult: API.Result = await chooseTenantSubmit({
tenantId: tenantList[0].id as number,
});
......@@ -161,11 +161,6 @@ const Login: React.FC = () => {
}
};
const setTenantCookie = (tenantId: number) => {
localStorage.setItem('dlink-tenantId', tenantId.toString()); // 放入本地存储中 request2请求时会放入header
cookies.set('tenantId', tenantId.toString(), { path: '/' }); // 放入cookie中
};
const handleShowTenant = () => {
return (
<>
......@@ -207,7 +202,7 @@ const Login: React.FC = () => {
onChange={(value) => {
if (value) {
setCheckDisabled(false); // 如果没选择租户 ·确认按钮· 则禁用
setTenantCookie(value as number);
setTenantStorageAndCookie(value as number);
setTenantIdParams(value as number);
} else {
setCheckDisabled(true);
......
......@@ -31,8 +31,8 @@ enum ErrorShowType {
interface ResponseStructure {
success: boolean;
data: any;
errorCode?: number;
errorMessage?: string;
code?: number;
msg?: string;
showType?: ErrorShowType;
}
......@@ -46,12 +46,11 @@ export const errorConfig: RequestConfig = {
errorConfig: {
// 错误抛出
errorThrower: (res) => {
const { success, data, errorCode, errorMessage, showType } =
res as unknown as ResponseStructure;
const { success, data, code, msg, showType } = res as unknown as ResponseStructure;
if (!success) {
const error: any = new Error(errorMessage);
const error: any = new Error(msg);
error.name = 'BizError';
error.info = { errorCode, errorMessage, showType, data };
error.info = { code, msg, showType, data };
throw error; // 抛出自制的错误
}
},
......@@ -62,28 +61,28 @@ export const errorConfig: RequestConfig = {
if (error.name === 'BizError') {
const errorInfo: ResponseStructure | undefined = error.info;
if (errorInfo) {
const { errorMessage, errorCode } = errorInfo;
const { msg, code } = errorInfo;
switch (errorInfo.showType) {
case ErrorShowType.SILENT:
// do nothing
break;
case ErrorShowType.WARN_MESSAGE:
message.warning(errorMessage);
message.warning(msg);
break;
case ErrorShowType.ERROR_MESSAGE:
message.error(errorMessage);
message.error(msg);
break;
case ErrorShowType.NOTIFICATION:
notification.open({
description: errorMessage,
message: errorCode,
description: msg,
message: code,
});
break;
case ErrorShowType.REDIRECT:
// TODO: redirect
break;
default:
message.error(errorMessage);
message.error(msg);
}
}
} else if (error.response) {
......
......@@ -17,7 +17,8 @@
import { request } from '@umijs/max';
/** 获取当前的用户 GET /api/current */
// ================================ About Account ================================
/** GET /api/current */
export async function currentUser(options?: { [key: string]: any }) {
return request<API.Result>('/api/current', {
method: 'GET',
......@@ -25,7 +26,7 @@ export async function currentUser(options?: { [key: string]: any }) {
});
}
/** 退出登录接口 POST /api/outLogin */
/** DELETE /api/outLogin */
export async function outLogin(options?: { [key: string]: any }) {
return request<Record<string, any>>('/api/outLogin', {
method: 'DELETE',
......@@ -33,7 +34,7 @@ export async function outLogin(options?: { [key: string]: any }) {
});
}
/** 登录接口 POST /api/login */
/** POST /api/login */
export async function login(body: API.LoginParams, options?: { [key: string]: any }) {
return request<API.Result>('/api/login', {
method: 'POST',
......@@ -45,7 +46,7 @@ export async function login(body: API.LoginParams, options?: { [key: string]: an
});
}
/** 获取当前的用户 GET /api/current */
/** GET /api/current */
export function chooseTenantSubmit(params: { tenantId: number }) {
return request<API.Result>('/api/chooseTenant', {
method: 'GET',
......@@ -54,3 +55,69 @@ export function chooseTenantSubmit(params: { tenantId: number }) {
},
});
}
// ============================ CRUD REQUEST ============================
export async function queryData(url: string, params?: PublicParams.TableParams) {
return request(url, {
method: 'POST',
data: {
...params,
},
});
}
export async function getData(url: string, params?: any) {
return request(url, {
method: 'GET',
params: {
...params,
},
});
}
export async function removeData(url: string, params: any[]) {
return request(url, {
method: 'DELETE',
data: {
...params,
},
});
}
export async function addOrUpdateData(url: string, params: any) {
return request(url, {
method: 'PUT',
data: {
...params,
},
});
}
export async function postDataArray(url: string, params: number[]) {
return request(url, {
method: 'POST',
data: {
...params,
},
});
}
export async function postAll(url: string, params?: any) {
return request(url, {
method: 'POST',
data: {
...params,
},
});
}
export async function getInfoById(url: string, id: number) {
return request(url, {
method: 'GET',
params: {
id: id,
},
});
}
// =========================== Business ===================================
......@@ -15,4 +15,12 @@
* limitations under the License.
*/
/**
* user tenant id
*/
export const TENANT_ID = 'tenantId';
/**
* the platform version
*/
export const VERSION = '0.8.0';
......@@ -54,3 +54,16 @@ declare namespace API {
username?: string;
};
}
declare namespace PublicParams {
export type TableParams = {
status?: string;
name?: string;
desc?: string;
key?: number;
pageSize?: number;
currentPage?: number;
filter?: Record<string, any[]>;
sorter?: Record<string, any>;
};
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { TENANT_ID } from '@/services/constants';
import cookies from 'js-cookie';
/**
* PUT tenantId TO localStorage & cookies
* @param tenantId
*/
export function setTenantStorageAndCookie(tenantId: number) {
// save as localStorage
localStorage.setItem(TENANT_ID, tenantId.toString());
// save as cookies
cookies.set(TENANT_ID, tenantId.toString(), { path: '/' });
}
/**
* get tenant id
* @param tenantId
*/
export function getTenantByLocalStorage() {
return localStorage.getItem(TENANT_ID);
}
/**
* parseJsonStr
* @param jsonStr
*/
export function parseJsonStr(jsonStr: string) {
return JSON.parse(JSON.stringify(jsonStr));
}
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