umi-request 替换为 axios

This commit is contained in:
whyour 2023-07-17 23:13:06 +08:00
parent bd166ee794
commit efd4f1d5ab
32 changed files with 215 additions and 214 deletions

View File

@ -261,7 +261,8 @@ export default class SystemService {
const dataFile = fs.createReadStream(config.dataTgzFile);
res.writeHead(200, {
'Content-Type': 'application/force-download',
'Content-Disposition': 'attachment; filename=data.tgz'
'Content-Disposition': 'attachment; filename=data.tgz',
'Content-length': fs.statSync(config.dataTgzFile).size
});
dataFile.pipe(res);
} catch (error: any) {

View File

@ -132,6 +132,7 @@
"ansi-to-react": "^6.1.6",
"antd": "^4.24.8",
"antd-img-crop": "^4.2.3",
"axios": "^1.4.0",
"codemirror": "^5.65.2",
"compression-webpack-plugin": "9.2.0",
"concurrently": "^7.0.0",
@ -158,7 +159,6 @@
"tslib": "^2.4.0",
"tsx": "^3.12.3",
"typescript": "4.8.4",
"umi-request": "^1.4.0",
"vh-check": "^2.0.5",
"virtualizedtableforantd4": "1.3.0",
"webpack": "^5.70.0",

View File

@ -228,6 +228,9 @@ devDependencies:
antd-img-crop:
specifier: ^4.2.3
version: 4.12.2(antd@4.24.10)(react-dom@18.2.0)(react@18.2.0)
axios:
specifier: ^1.4.0
version: 1.4.0
codemirror:
specifier: ^5.65.2
version: 5.65.13
@ -306,9 +309,6 @@ devDependencies:
typescript:
specifier: 4.8.4
version: 4.8.4
umi-request:
specifier: ^1.4.0
version: 1.4.0
vh-check:
specifier: ^2.0.5
version: 2.0.5
@ -5856,6 +5856,16 @@ packages:
- debug
dev: true
/axios@1.4.0:
resolution: {integrity: sha512-S4XCWMEmzvo64T9GfvQDOXgYRDJ/wsSZc7Jvdgx5u1sd0JwsuPLqb3SYmusag+edF6ziyMensPVqLTSc1PiSEA==}
dependencies:
follow-redirects: 1.15.2
form-data: 4.0.0
proxy-from-env: 1.1.0
transitivePeerDependencies:
- debug
dev: true
/babel-jest@29.5.0:
resolution: {integrity: sha512-mA4eCDh5mSo2EcA9xQjVTpmbbNk32Zb3Q3QFQsNhaK56Q+yoXowzFodLux30HRgyOho5rsQ6B0P9QpMkvvnJ0Q==}
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
@ -7431,8 +7441,11 @@ packages:
/encoding@0.1.13:
resolution: {integrity: sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==}
requiresBuild: true
dependencies:
iconv-lite: 0.6.3
dev: false
optional: true
/end-of-stream@1.4.4:
resolution: {integrity: sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==}
@ -9354,13 +9367,6 @@ packages:
engines: {node: '>=0.10.0'}
dev: true
/isomorphic-fetch@2.2.1:
resolution: {integrity: sha512-9c4TNAKYXM5PRyVcwUZrF3W09nQ+sO7+jydgs4ZGW9dhsLG2VOlISJABombdQqQRXCwuYG3sYV/puGf5rp0qmA==}
dependencies:
node-fetch: 1.7.3
whatwg-fetch: 3.6.2
dev: true
/isomorphic-unfetch@4.0.2:
resolution: {integrity: sha512-1Yd+CF/7al18/N2BDbsLBcp6RO3tucSW+jcLq24dqdX5MNbCNTw1z4BsGsp4zNmjr/Izm2cs/cEqZPp4kvWSCA==}
dependencies:
@ -10402,13 +10408,6 @@ packages:
engines: {node: '>=10.5.0'}
dev: true
/node-fetch@1.7.3:
resolution: {integrity: sha512-NhZ4CsKx7cYm2vSrBAr2PvFOe6sWDf0UYLRqA6svUYg7+/TSfVAu49jYC4BvQ4Sms9SZgdqGBgroqfDhJdTyKQ==}
dependencies:
encoding: 0.1.13
is-stream: 1.1.0
dev: true
/node-fetch@2.6.11:
resolution: {integrity: sha512-4I6pdBY1EthSqDmJkiNk3JIT8cswwR9nfeW/cPdUagJYEQG7R95WRH74wpz7ma8Gh/9dI9FP+OU+0E4FvtA55w==}
engines: {node: 4.x || >=6.0.0}
@ -14742,13 +14741,6 @@ packages:
hasBin: true
dev: true
/umi-request@1.4.0:
resolution: {integrity: sha512-OknwtQZddZHi0Ggi+Vr/olJ7HNMx4AzlywyK0W3NZBT7B0stjeZ9lcztA85dBgdAj3KVk8uPJPZSnGaDjELhrA==}
dependencies:
isomorphic-fetch: 2.2.1
qs: 6.11.2
dev: true
/umi@4.0.70(@types/node@17.0.45)(@types/react@18.2.8)(eslint@8.35.0)(prettier@2.8.8)(react-dom@18.2.0)(react@18.2.0)(sockjs-client@1.6.1)(stylelint@14.8.2)(typescript@4.8.4)(webpack@5.85.1):
resolution: {integrity: sha512-e6GwzZXC1U+XPJhLaOMIr6IBWpi8mGap6ExRkApidfbYZ8HxilvrVHnaLUYSykp206RhZBnJWI7r99mYu3e5eQ==}
engines: {node: '>=14'}
@ -15237,10 +15229,6 @@ packages:
resolution: {integrity: sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==}
engines: {node: '>=0.8.0'}
/whatwg-fetch@3.6.2:
resolution: {integrity: sha512-bJlen0FcuU/0EMLrdbJ7zOnW6ITZLrZMIarMUVmdKtsGvZna8vxKYaexICWPfZ8qwf9fzNq+UEIZrnSaApt6RA==}
dev: true
/whatwg-url@5.0.0:
resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}
dependencies:

View File

@ -51,9 +51,7 @@ const Config = () => {
: value;
request
.post(`${config.apiPrefix}configs/save`, {
data: { content, name: select },
})
.post(`${config.apiPrefix}configs/save`, { content, name: select })
.then(({ code, data }) => {
if (code === 200) {
message.success('保存成功');

View File

@ -184,11 +184,9 @@ const CronDetailModal = ({
return new Promise((resolve, reject) => {
request
.put(`${config.apiPrefix}scripts`, {
data: {
filename: scriptInfo.filename,
path: scriptInfo.parent || '',
content,
},
})
.then(({ code, data }) => {
if (code === 200) {
@ -220,7 +218,7 @@ const CronDetailModal = ({
),
onOk() {
request
.put(`${config.apiPrefix}crons/run`, { data: [currentCron.id] })
.put(`${config.apiPrefix}crons/run`, [currentCron.id])
.then(({ code, data }) => {
if (code === 200) {
setCurrentCron({ ...currentCron, status: CrontabStatus.running });
@ -250,7 +248,7 @@ const CronDetailModal = ({
),
onOk() {
request
.put(`${config.apiPrefix}crons/stop`, { data: [currentCron.id] })
.put(`${config.apiPrefix}crons/stop`, [currentCron.id] )
.then(({ code, data }) => {
if (code === 200) {
setCurrentCron({ ...currentCron, status: CrontabStatus.idle });
@ -282,9 +280,7 @@ const CronDetailModal = ({
`${config.apiPrefix}crons/${
currentCron.isDisabled === 1 ? 'enable' : 'disable'
}`,
{
data: [currentCron.id],
},
[currentCron.id],
)
.then(({ code, data }) => {
if (code === 200) {
@ -320,9 +316,7 @@ const CronDetailModal = ({
`${config.apiPrefix}crons/${
currentCron.isPinned === 1 ? 'unpin' : 'pin'
}`,
{
data: [currentCron.id],
},
[currentCron.id],
)
.then(({ code, data }) => {
if (code === 200) {

View File

@ -457,7 +457,7 @@ const Crontab = () => {
),
onOk() {
request
.put(`${config.apiPrefix}crons/run`, { data: [record.id] })
.put(`${config.apiPrefix}crons/run`, [record.id])
.then(({ code, data }) => {
if (code === 200) {
const result = [...value];
@ -492,7 +492,7 @@ const Crontab = () => {
),
onOk() {
request
.put(`${config.apiPrefix}crons/stop`, { data: [record.id] })
.put(`${config.apiPrefix}crons/stop`, [record.id])
.then(({ code, data }) => {
if (code === 200) {
const result = [...value];
@ -533,9 +533,7 @@ const Crontab = () => {
`${config.apiPrefix}crons/${
record.isDisabled === 1 ? 'enable' : 'disable'
}`,
{
data: [record.id],
},
[record.id],
)
.then(({ code, data }) => {
if (code === 200) {
@ -577,9 +575,7 @@ const Crontab = () => {
`${config.apiPrefix}crons/${
record.isPinned === 1 ? 'unpin' : 'pin'
}`,
{
data: [record.id],
},
[record.id],
)
.then(({ code, data }) => {
if (code === 200) {
@ -725,9 +721,10 @@ const Crontab = () => {
content: <>{OperationName[operationStatus]}</>,
onOk() {
request
.put(`${config.apiPrefix}crons/${OperationPath[operationStatus]}`, {
data: selectedRowIds,
})
.put(
`${config.apiPrefix}crons/${OperationPath[operationStatus]}`,
selectedRowIds,
)
.then(({ code, data }) => {
if (code === 200) {
getCrons();

View File

@ -25,9 +25,10 @@ const CronModal = ({
payload.id = cron.id;
}
try {
const { code, data } = await request[method](`${config.apiPrefix}crons`, {
data: payload,
});
const { code, data } = await request[method](
`${config.apiPrefix}crons`,
payload,
);
if (code === 200) {
message.success(cron ? '更新Cron成功' : '新建Cron成功');
@ -130,9 +131,7 @@ const CronLabelModal = ({
try {
const { code, data } = await request[action](
`${config.apiPrefix}crons/labels`,
{
data: payload,
},
payload,
);
if (code === 200) {

View File

@ -80,9 +80,7 @@ const ViewCreateModal = ({
try {
const { code, data } = await request[method](
`${config.apiPrefix}crons/views`,
{
data: view ? { ...values, id: view.id } : values,
},
view ? { ...values, id: view.id } : values,
);
if (code === 200) {

View File

@ -168,9 +168,9 @@ const ViewManageModal = ({
const onShowChange = (checked: boolean, record: any, index: number) => {
request
.put(`${config.apiPrefix}crons/views/${checked ? 'enable' : 'disable'}`, {
data: [record.id],
})
.put(`${config.apiPrefix}crons/views/${checked ? 'enable' : 'disable'}`, [
record.id,
])
.then(({ code, data }) => {
if (code === 200) {
const _list = [...list];
@ -195,7 +195,9 @@ const ViewManageModal = ({
const dragRow = list[dragIndex];
request
.put(`${config.apiPrefix}crons/views/move`, {
data: { fromIndex: dragIndex, toIndex: hoverIndex, id: dragRow.id },
fromIndex: dragIndex,
toIndex: hoverIndex,
id: dragRow.id,
})
.then(({ code, data }) => {
if (code === 200) {

View File

@ -269,9 +269,7 @@ const Dependence = () => {
),
onOk() {
request
.put(`${config.apiPrefix}dependencies/reinstall`, {
data: [record.id],
})
.put(`${config.apiPrefix}dependencies/reinstall`, [record.id])
.then(({ code, data }) => {
if (code === 200) {
handleDependence(data[0]);
@ -342,9 +340,7 @@ const Dependence = () => {
content: <></>,
onOk() {
request
.put(`${config.apiPrefix}dependencies/reinstall`, {
data: selectedRowIds,
})
.put(`${config.apiPrefix}dependencies/reinstall`, selectedRowIds)
.then(({ code, data }) => {
if (code === 200) {
setSelectedRowIds([]);

View File

@ -48,9 +48,7 @@ const DependenceModal = ({
try {
const { code, data } = await request[method](
`${config.apiPrefix}dependencies`,
{
data: payload,
},
payload,
);
if (code === 200) {
@ -122,7 +120,11 @@ const DependenceModal = ({
name="name"
label="名称"
rules={[
{ required: true, message: '请输入依赖名称,支持指定版本', whitespace: true },
{
required: true,
message: '请输入依赖名称,支持指定版本',
whitespace: true,
},
]}
>
<Input.TextArea

View File

@ -48,7 +48,8 @@ const Diff = () => {
request
.post(`${config.apiPrefix}configs/save`, {
data: { content, name: current },
content,
name: current,
})
.then(({ code, data }) => {
if (code === 200) {

View File

@ -19,10 +19,8 @@ const EditNameModal = ({
setLoading(true);
try {
const { code, data } = await request.put(`${config.apiPrefix}envs/name`, {
data: {
ids,
name: values.name,
},
});
if (code === 200) {

View File

@ -248,9 +248,7 @@ const Env = () => {
`${config.apiPrefix}envs/${
record.status === Status. ? 'enable' : 'disable'
}`,
{
data: [record.id],
},
[record.id],
)
.then(({ code, data }) => {
if (code === 200) {
@ -388,7 +386,8 @@ const Env = () => {
const dragRow = value[dragIndex];
request
.put(`${config.apiPrefix}envs/${dragRow.id}/move`, {
data: { fromIndex: dragIndex, toIndex: hoverIndex },
fromIndex: dragIndex,
toIndex: hoverIndex,
})
.then(({ code, data }) => {
if (code === 200) {
@ -438,9 +437,10 @@ const Env = () => {
content: <>{OperationName[operationStatus]}</>,
onOk() {
request
.put(`${config.apiPrefix}envs/${OperationPath[operationStatus]}`, {
data: selectedRowIds,
})
.put(
`${config.apiPrefix}envs/${OperationPath[operationStatus]}`,
selectedRowIds,
)
.then(({ code, data }) => {
if (code === 200) {
getEnvs();
@ -477,9 +477,7 @@ const Env = () => {
try {
const { code, data } = await request.post(
`${config.apiPrefix}envs/upload`,
{
data: formData,
},
formData,
);
if (code === 200) {

View File

@ -37,9 +37,10 @@ const EnvModal = ({
payload = { ...values, id: env.id };
}
try {
const { code, data } = await request[method](`${config.apiPrefix}envs`, {
data: payload,
});
const { code, data } = await request[method](
`${config.apiPrefix}envs`,
payload,
);
if (code === 200) {
message.success(env ? '更新变量成功' : '新建变量成功');

View File

@ -36,10 +36,8 @@ const Initialization = () => {
setLoading(true);
request
.put(`${config.apiPrefix}user/init`, {
data: {
username: values.username,
password: values.password,
},
})
.then(({ code, data }) => {
if (code === 200) {
@ -53,9 +51,7 @@ const Initialization = () => {
setLoading(true);
request
.put(`${config.apiPrefix}user/notification/init`, {
data: {
...values,
},
values,
})
.then(({ code, data }) => {
if (code === 200) {

View File

@ -35,10 +35,8 @@ const Login = () => {
setWaitTime(null);
request
.post(`${config.apiPrefix}user/login`, {
data: {
username: values.username,
password: values.password,
},
})
.then((data) => {
checkResponse(data, values);
@ -54,7 +52,8 @@ const Login = () => {
setVerifying(true);
request
.put(`${config.apiPrefix}user/two-factor/login`, {
data: { ...loginInfo, code: values.code },
...loginInfo,
code: values.code,
})
.then((data: any) => {
checkResponse(data);

View File

@ -86,11 +86,9 @@ const EditModal = ({
const content = editorRef.current.getValue().replace(/\r\n/g, '\n');
request
.put(`${config.apiPrefix}scripts/run`, {
data: {
filename: cNode.title,
path: cNode.parent || '',
content,
},
})
.then(({ code, data }) => {
if (code === 200) {
@ -106,11 +104,9 @@ const EditModal = ({
}
request
.put(`${config.apiPrefix}scripts/stop`, {
data: {
filename: cNode.title,
path: cNode.parent || '',
pid: currentPid,
},
})
.then(({ code, data }) => {
if (code === 200) {

View File

@ -44,9 +44,7 @@ const EditScriptNameModal = ({
formData.append('content', '');
formData.append('directory', directory);
request
.post(`${config.apiPrefix}scripts`, {
data: formData,
})
.post(`${config.apiPrefix}scripts`, formData)
.then(({ code, data }) => {
if (code === 200) {
message.success(directory ? '新建文件夹成功' : '新建文件成功');

View File

@ -223,11 +223,9 @@ const Script = () => {
return new Promise((resolve, reject) => {
request
.put(`${config.apiPrefix}scripts`, {
data: {
filename: currentNode.title,
path: currentNode.parent || '',
content,
},
})
.then(({ code, data }) => {
if (code === 200) {
@ -341,9 +339,7 @@ const Script = () => {
const downloadFile = () => {
request
.post(`${config.apiPrefix}scripts/download`, {
data: {
filename: currentNode.title,
},
})
.then(({ code, data }) => {
if (code === 200) {

View File

@ -21,12 +21,10 @@ const RenameModal = ({
const { code, data } = await request.put(
`${config.apiPrefix}scripts/rename`,
{
data: {
filename: currentNode.title,
path: currentNode.parent || '',
newFilename: values.name,
},
},
);
if (code === 200) {

View File

@ -19,9 +19,7 @@ const SaveModal = ({
setLoading(true);
const payload = { ...file, ...values, originFilename: file.title };
request
.post(`${config.apiPrefix}scripts`, {
data: payload,
})
.post(`${config.apiPrefix}scripts`, payload)
.then(({ code, data }) => {
if (code === 200) {
message.success('保存文件成功');

View File

@ -19,9 +19,7 @@ const SettingModal = ({
setLoading(true);
const payload = { ...file, ...values };
request
.post(`${config.apiPrefix}scripts`, {
data: payload,
})
.post(`${config.apiPrefix}scripts`, payload)
.then(({ code, data }) => {
if (code === 200) {
message.success('保存文件成功');

View File

@ -23,9 +23,10 @@ const AppModal = ({
payload.id = app.id;
}
try {
const { code, data } = await request[method](`${config.apiPrefix}apps`, {
data: payload,
});
const { code, data } = await request[method](
`${config.apiPrefix}apps`,
payload,
);
if (code === 200) {
message.success(app ? '更新应用成功' : '新建应用成功');

View File

@ -129,7 +129,7 @@ const CheckUpdate = ({ socketMessage, systemInfo }: any) => {
okText: '重启',
onOk() {
request
.put(`${config.apiPrefix}system/reload`, { data: { type: 'system' } })
.put(`${config.apiPrefix}system/reload`, { type: 'system' })
.then((_data: any) => {
message.success({
content: (

View File

@ -20,9 +20,7 @@ const NotificationSetting = ({ data }: any) => {
request
.put(`${config.apiPrefix}user/notification`, {
data: {
...values,
},
values,
})
.then(({ code, data }) => {
if (code === 200) {

View File

@ -19,6 +19,7 @@ import { saveAs } from 'file-saver';
import './index.less';
import { UploadOutlined } from '@ant-design/icons';
import Countdown from 'antd/lib/statistic/Countdown';
import useProgress from './progress';
const optionsWithDisabled = [
{ label: '亮色', value: 'light' },
@ -39,6 +40,8 @@ const Other = ({
const [form] = Form.useForm();
const modalRef = useRef<any>();
const [exportLoading, setExportLoading] = useState(false);
const showUploadProgress = useProgress('上传');
const showDownloadProgress = useProgress('下载');
const {
enable: enableDarkMode,
@ -78,9 +81,7 @@ const Other = ({
const updateSystemConfig = () => {
request
.put(`${config.apiPrefix}system/config`, {
data: { ...systemConfig },
})
.put(`${config.apiPrefix}system/config`, systemConfig)
.then(({ code, data }) => {
if (code === 200) {
message.success('更新成功');
@ -94,7 +95,18 @@ const Other = ({
const exportData = () => {
setExportLoading(true);
request
.put(`${config.apiPrefix}system/data/export`, { responseType: 'blob' })
.put<Blob>(
`${config.apiPrefix}system/data/export`,
{},
{
responseType: 'blob',
onDownloadProgress: (e) => {
if (e.progress) {
showDownloadProgress(parseFloat((e.progress * 100).toFixed(1)));
}
},
},
)
.then((res) => {
saveAs(res, 'data.tgz');
})
@ -104,34 +116,6 @@ const Other = ({
.finally(() => setExportLoading(false));
};
const showUploadModal = (progress: number) => {
if (modalRef.current) {
modalRef.current.update({
content: (
<Progress
style={{ display: 'flex', justifyContent: 'center' }}
type="circle"
percent={progress}
/>
),
});
} else {
modalRef.current = Modal.info({
width: 600,
maskClosable: false,
title: '上传中...',
centered: true,
content: (
<Progress
style={{ display: 'flex', justifyContent: 'center' }}
type="circle"
percent={progress}
/>
),
});
}
};
const showReloadModal = () => {
Modal.confirm({
width: 600,
@ -142,8 +126,8 @@ const Other = ({
okText: '重启',
onOk() {
request
.put(`${config.apiPrefix}system/reload`, { data: { type: 'data' } })
.then((_data: any) => {
.put(`${config.apiPrefix}system/reload`, { type: 'data' })
.then(() => {
message.success({
content: (
<span>
@ -231,8 +215,7 @@ const Other = ({
action="/api/system/data/import"
onChange={(e) => {
if (e.event?.percent) {
const percent = parseFloat(e.event?.percent.toFixed(1));
showUploadModal(percent);
showUploadProgress(parseFloat(e.event?.percent.toFixed(1)));
if (e.event?.percent === 100) {
showReloadModal();
}

View File

@ -0,0 +1,33 @@
import { Modal, Progress } from 'antd';
import { useRef } from 'react';
export default function useProgress(title: string) {
const modalRef = useRef<ReturnType<typeof Modal.info>>();
const ProgressElement = ({ percent }: { percent: number }) => (
<Progress
style={{ display: 'flex', justifyContent: 'center' }}
type="circle"
percent={percent}
/>
);
const showProgress = (percent: number) => {
if (modalRef.current) {
modalRef.current.update({
title: `${title}${percent >= 100 ? '成功' : '中...'}`,
content: <ProgressElement percent={percent} />,
});
} else {
modalRef.current = Modal.info({
width: 600,
maskClosable: false,
title: `${title}${percent >= 100 ? '成功' : '中...'}`,
centered: true,
content: <ProgressElement percent={percent} />,
});
}
};
return showProgress;
}

View File

@ -22,10 +22,8 @@ const SecuritySettings = ({ user, userChange }: any) => {
const handleOk = (values: any) => {
request
.put(`${config.apiPrefix}user`, {
data: {
username: values.username,
password: values.password,
},
})
.then(({ code, data }) => {
if (code === 200) {
@ -64,7 +62,7 @@ const SecuritySettings = ({ user, userChange }: any) => {
const completeTowFactor = () => {
setLoading(true);
request
.put(`${config.apiPrefix}user/two-factor/active`, { data: { code } })
.put(`${config.apiPrefix}user/two-factor/active`, { code })
.then(({ code, data }) => {
if (code === 200) {
if (data) {

View File

@ -254,7 +254,7 @@ const Subscription = () => {
),
onOk() {
request
.put(`${config.apiPrefix}subscriptions/run`, { data: [record.id] })
.put(`${config.apiPrefix}subscriptions/run`, [record.id])
.then(({ code, data }) => {
if (code === 200) {
const result = [...value];
@ -289,7 +289,7 @@ const Subscription = () => {
),
onOk() {
request
.put(`${config.apiPrefix}subscriptions/stop`, { data: [record.id] })
.put(`${config.apiPrefix}subscriptions/stop`, [record.id])
.then(({ code, data }) => {
if (code === 200) {
const result = [...value];
@ -386,9 +386,7 @@ const Subscription = () => {
`${config.apiPrefix}subscriptions/${
record.is_disabled === 1 ? 'enable' : 'disable'
}`,
{
data: [record.id],
},
[record.id],
)
.then(({ code, data }) => {
if (code === 200) {

View File

@ -47,9 +47,7 @@ const SubscriptionModal = ({
try {
const { code, data } = await request[method](
`${config.apiPrefix}subscriptions`,
{
data: payload,
},
payload,
);
if (code === 200) {
message.success(subscription ? '更新订阅成功' : '新建订阅成功');

View File

@ -1,17 +1,36 @@
import { extend } from 'umi-request';
import { message } from 'antd';
import config from './config';
import { history } from '@umijs/max';
import axios, {
AxiosError,
AxiosInstance,
AxiosRequestConfig,
} from 'axios';
interface IResponseData {
code?: number;
data?: any;
message?: string;
}
type Override<
T,
K extends Partial<{ [P in keyof T]: any }> | string,
> = K extends string
? Omit<T, K> & { [P in keyof T]: T[P] | unknown }
: Omit<T, keyof K> & K;
message.config({
duration: 2,
});
const time = Date.now();
const errorHandler = function (error: any) {
const errorHandler = function (
error: AxiosError,
) {
if (error.response) {
const msg = error.data
? error.data.message || error.message || error.data
const msg = error.response.data
? error.response.data.message || error.message || error.response.data
: error.response.statusText;
const responseStatus = error.response.status;
if ([502, 504].includes(responseStatus)) {
@ -32,10 +51,14 @@ const errorHandler = function (error: any) {
console.log(error.message);
}
throw error; // 如果throw. 错误将继续抛出.
return Promise.reject(error);
};
const _request = extend({ timeout: 60000, params: { t: time }, errorHandler });
let _request = axios.create({
timeout: 60000,
params: { t: time },
});
const apiWhiteList = [
'/api/user/login',
'/open/auth/token',
@ -45,15 +68,13 @@ const apiWhiteList = [
'/api/user/notification/init',
];
_request.interceptors.request.use((url, options) => {
_request.interceptors.request.use((_config) => {
const token = localStorage.getItem(config.authKey);
if (token && !apiWhiteList.includes(url)) {
const headers = {
Authorization: `Bearer ${token}`,
};
return { url, options: { ...options, headers } };
if (token && !apiWhiteList.includes(_config.url!)) {
_config.headers.Authorization = `Bearer ${token}`;
return _config;
}
return { url, options };
return _config;
});
_request.interceptors.response.use(async (response) => {
@ -67,7 +88,7 @@ _request.interceptors.response.use(async (response) => {
}
} else {
try {
const res = await response.clone().json();
const res = response.data;
if (res.code !== 200) {
const msg = res.message || res.data;
msg &&
@ -81,6 +102,25 @@ _request.interceptors.response.use(async (response) => {
return response;
}
return response;
});
}, errorHandler);
export const request = _request;
export const request = _request as Override<AxiosInstance, {
get<T = IResponseData, D = any>(
url: string,
config?: AxiosRequestConfig<D>,
): Promise<T>;
delete<T = IResponseData, D = any>(
url: string,
config?: AxiosRequestConfig<D>,
): Promise<T>;
post<T = IResponseData, D = any>(
url: string,
data?: D,
config?: AxiosRequestConfig<D>,
): Promise<T>;
put<T = IResponseData, D = any>(
url: string,
data?: D,
config?: AxiosRequestConfig<D>,
): Promise<T>;
}>;