Skip to content

Commit

Permalink
feat: 代码优化
Browse files Browse the repository at this point in the history
  • Loading branch information
lingting committed Dec 6, 2021
1 parent 6822357 commit a97d823
Show file tree
Hide file tree
Showing 8 changed files with 166 additions and 157 deletions.
1 change: 1 addition & 0 deletions config/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
},
{
path: '/',
layout: false,
component: '../layouts',
routes: [
// {
Expand Down
16 changes: 0 additions & 16 deletions src/access.ts

This file was deleted.

135 changes: 8 additions & 127 deletions src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import { PageLoading } from '@ant-design/pro-layout';
import { notification } from 'antd';
import type { RequestConfig } from 'umi';
import type { RequestInterceptor, ResponseError, ResponseInterceptor } from 'umi-request';
import type { GLOBAL } from '@/typings';
import { User, Token, LayoutSetting } from '@/utils/Ballcat';
import I18n from './utils/I18nUtils';
import Notify from './utils/NotifyUtils';
import { settings } from './utils/ConfigUtils';

// const isDev = process.env.NODE_ENV === 'development';
import { User, LayoutSetting } from '@/utils/Ballcat';
import { settings } from '@/utils/ConfigUtils';
import ProjectRequestConfig from '@/utils/RequestConfig';
import { AliveScope } from 'react-activation';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
Expand All @@ -31,127 +27,12 @@ export async function getInitialState(): Promise<GLOBAL.Is> {
return { ...is };
}

/**
* 自定义拦截请求
*/
const customerRequestInterceptor: RequestInterceptor = (url, options) => {
// 处理请求地址
const newUrl = `/api/${url.startsWith('/') ? url.substring(1) : url}`;
const headers: any = { ...options.headers };

// 添加token
const token = Token.get();
if (!headers.Authorization && token) {
headers.Authorization = `Bearer ${token}`;
}

// 添加语言
if (!headers['Accept-Language']) {
headers['Accept-Language'] = I18n.getLocal();
}

return { url: newUrl, options: { ...options, headers } };
};

/**
* 自定义处理返回值
*/
const customerResponseInterceptor: ResponseInterceptor = async (res, option) => {
// 返回值不是json
let isJson = false;

res.headers.forEach((v, k) => {
if (k.toLowerCase() === 'content-type') {
if (v.indexOf('application/json') !== -1) {
isJson = true;
}
}
});

// 仅处理json数据
return !isJson
? res
: res
.clone()
.json()
.then((json) => {
const response = res;

if (option.url) {
// 部分接口特殊处理
if (option.url === 'captcha/get' || option.url === 'captcha/check') {
return response;
}
}

if (response.status === 401) {
// token 鉴权异常
Notify.logout();
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw {
response,
data: json,
message: json.message || json.error,
};
}

if (json && json.code !== 200) {
// 登录接口, 通过是否存在token判断成功或失败
if (option.url === 'oauth/token' && json.access_token) {
return response;
}

// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw {
response,
data: json,
message: json.message || json.error,
};
}

return response;
});
};
const errorHandler = (error: ResponseError) => {
const { response, message: msg } = error;
if (!response) {
notification.error({
description: I18n.text('app.error.network.description'),
message: I18n.text('app.error.network'),
});
} else {
notification.error({
description: (
<>
{response.status === 401 ? (
<>
{I18n.text('app.error.permissions.description')}
<br />
</>
) : undefined}
{msg}
</>
),
message: I18n.text(
response.status === 401 ? 'app.error.permissions' : 'global.operation.failed',
),
});
}
throw error;
};
export function rootContainer(container: any) {
return <AliveScope>{container}</AliveScope>;
}

/**
* 请求增强
* @see https://beta-pro.ant.design/docs/request-cn
*/
export const request: RequestConfig = {
requestType: 'json',
requestInterceptors: [customerRequestInterceptor],
responseInterceptors: [customerResponseInterceptor],
errorConfig: {
adaptor: () => {
return { success: true };
},
},
errorHandler,
};
export const request: RequestConfig = { ...ProjectRequestConfig };
19 changes: 8 additions & 11 deletions src/layouts/BasicLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import type { ExpandRoute } from '@/utils/RouteUtils';
import RouteUtils, { goto } from '@/utils/RouteUtils';
import I18n from '@/utils/I18nUtils';
import Icon from '@/components/Icon';
import { AliveScope } from 'react-activation';
import MultiTab from '@/components/MultiTab';
import { KeepAlive as ReactKeepAlive } from 'react-activation';
import Notify from '@/utils/NotifyUtils';
Expand Down Expand Up @@ -165,16 +164,14 @@ const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
}}
>
{initialState?.settings?.multiTab && <MultiTab />}
<AliveScope>
<WaterMark
content={settings.waterMark ? initialState?.user?.info?.nickname : undefined}
style={{ height: '100%' }}
>
<ReactKeepAlive id={keepAliveProps.id} name={keepAliveProps.name}>
{children}
</ReactKeepAlive>
</WaterMark>
</AliveScope>
<WaterMark
content={settings.waterMark ? initialState?.user?.info?.nickname : undefined}
style={{ height: '100%' }}
>
<ReactKeepAlive id={keepAliveProps.id} name={keepAliveProps.name}>
{children}
</ReactKeepAlive>
</WaterMark>
</ProLayout>
);
};
Expand Down
3 changes: 2 additions & 1 deletion src/pages/user/Login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ const Login: React.FC = () => {
// 则刷新数据
await refresh();
I18n.success('pages.login.success');
history?.push(redirect || '/');
// history?.push(redirect || '/');
window.location.replace(redirect || '/');
})
.catch(() => {
I18n.error('pages.login.failure');
Expand Down
15 changes: 15 additions & 0 deletions src/utils/I18nUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ import type { ConfigOnClose } from 'antd/lib/message';
import { settings } from './ConfigUtils';
import { setLocale } from 'umi';

import zhCN from '@/locales/zh-CN';
import enUS from '@/locales/en-US';

const locales = {
zhCN,
enUS,
};

export type I18nParams =
| string
| {
Expand Down Expand Up @@ -34,6 +42,13 @@ const I18n = {
setLocale(local);
},
text: (key: string, params?: Record<string, string>, defaultMessage = key) => {
const lang = I18n.getLocal();
const locale = locales[lang.replace('-', '')];

if (locale && locale[key]) {
return locale[key];
}

if (I18n.getIntl()) {
return I18n.getIntl().formatMessage({ id: key, defaultMessage }, params);
}
Expand Down
4 changes: 2 additions & 2 deletions src/utils/NotifyUtils.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Modal } from 'antd';
import { announcement } from '@/services/ballcat/notify';
import { NotificationOutlined } from '@ant-design/icons';
import RouteUtils from './RouteUtils';
import I18n from './I18nUtils';
import { history } from 'umi';
import { Token, User } from './Ballcat';
Expand All @@ -13,7 +12,8 @@ const logoutHandler = () => {
Modal.destroyAll();
User.clean();
logoutModal = undefined;
RouteUtils.redirect('/user/login');
const { pathname } = history.location;
window.location.replace(`/user/login?redirect=${pathname}`);
};

const readNotice = (id: string) => {
Expand Down
130 changes: 130 additions & 0 deletions src/utils/RequestConfig.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { notification } from 'antd';
import type { RequestConfig } from 'umi';
import type { RequestInterceptor, ResponseError, ResponseInterceptor } from 'umi-request';
import { Token } from '@/utils/Ballcat';
import I18n from '@/utils/I18nUtils';
import Notify from '@/utils/NotifyUtils';

/**
* 自定义拦截请求
*/
const customerRequestInterceptor: RequestInterceptor = (url, options) => {
// 处理请求地址
const newUrl = `/api/${url.startsWith('/') ? url.substring(1) : url}`;
const headers: any = { ...options.headers };

// 添加token
const token = Token.get();
if (!headers.Authorization && token) {
headers.Authorization = `Bearer ${token}`;
}

// 添加语言
if (!headers['Accept-Language']) {
headers['Accept-Language'] = I18n.getLocal();
}

return { url: newUrl, options: { ...options, headers } };
};

/**
* 自定义处理返回值
*/
const customerResponseInterceptor: ResponseInterceptor = async (res, option) => {
// 返回值不是json
let isJson = false;

res.headers.forEach((v, k) => {
if (k.toLowerCase() === 'content-type') {
if (v.indexOf('application/json') !== -1) {
isJson = true;
}
}
});

// 仅处理json数据
return !isJson
? res
: res
.clone()
.json()
.then((json) => {
const response = res;

if (option.url) {
// 部分接口特殊处理
if (option.url === 'captcha/get' || option.url === 'captcha/check') {
return response;
}
}

if (response.status === 401) {
// token 鉴权异常
Notify.logout();
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw {
response,
data: json,
message: json.message || json.error,
};
}

if (json && json.code !== 200) {
// 登录接口, 通过是否存在token判断成功或失败
if (option.url === 'oauth/token' && json.access_token) {
return response;
}

// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw {
response,
data: json,
message: json.message || json.error,
};
}

return response;
});
};

const errorHandler = (error: ResponseError) => {
const { response, message: msg } = error;
if (!response) {
notification.error({
description: I18n.text('app.error.network.description'),
message: I18n.text('app.error.network'),
});
} else {
notification.error({
description: (
<>
{response.status === 401 ? (
<>
{I18n.text('app.error.permissions.description')}
<br />
</>
) : undefined}
{msg}
</>
),
message: I18n.text(
response.status === 401 ? 'app.error.permissions' : 'global.operation.failed',
),
});
}
throw error;
};

const request: RequestConfig = {
requestType: 'json',
requestInterceptors: [customerRequestInterceptor],
responseInterceptors: [customerResponseInterceptor],
errorConfig: {
adaptor: () => {
return { success: true };
},
},
errorHandler,
};

export default request;

0 comments on commit a97d823

Please sign in to comment.