123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- import { message } from 'antd';
- import { getApiUrl } from '@/utils/common';
- import {
- getLoginUrl,
- getUserSession,
- redirectToHome,
- redirectToLogin,
- } from '@/utils/user';
- export type RequestModel = {
- params?: object;
- headers?: object;
- signal?: AbortSignal;
- };
- export type RequestWithBodyModel = RequestModel & {
- body?: object | FormData;
- };
- const readResponse = async (response: Response) => {
- if (!response.headers) {
- return response;
- }
- const contentType = response.headers.get('content-type');
- const contentDisposition = response.headers.get('content-disposition');
- if (contentType === null) {
- return null;
- } else if (contentType.indexOf('application/json') !== -1) {
- return await response.json();
- } else if (contentType.indexOf('text/plain') !== -1) {
- return await response.text();
- } else if (
- contentDisposition != null &&
- contentDisposition.indexOf('attachment') !== -1
- ) {
- return await response.blob();
- } else {
- return response;
- }
- };
- const handleErrorResponse = async (err: Response) => {
- const error = await readResponse(err);
- let msg = error?.message || error?.errMessage || error;
- switch (err.status) {
- case 500:
- msg = '内部服务器错误,请稍后再试';
- break;
- case 401:
- redirectToLogin();
- return;
- case 403:
- msg = '资源拒绝授权访问';
- redirectToHome(1000);
- break;
- case 404:
- return;
- default:
- msg =
- typeof msg === 'string' && msg !== ''
- ? msg
- : '操作失败,请稍后再试,或联系技术人员';
- }
- message.error(msg)
- throw error;
- };
- export const useFetch = () => {
- const handleFetch = async (
- url: string,
- request: any,
- signal?: AbortSignal,
- ) => {
- const apiPrefix = getApiUrl();
- const requestUrl = `${apiPrefix}${url}${request?.params ? request.params : ''
- }`;
- const body = request?.body
- ? request.body instanceof FormData
- ? { ...request, body: request.body }
- : { ...request, body: JSON.stringify(request.body) }
- : request;
- const headers = {
- ...request?.headers,
- ...(!request?.body || !(request.body instanceof FormData)
- ? { 'Content-type': 'application/json' }
- : {}),
- Authorization: `Bearer ${getUserSession()}`,
- };
- return fetch(requestUrl, {
- ...body,
- headers,
- signal,
- })
- .then(async (response) => {
- if (!response.ok) {
- throw response;
- }
- const result = readResponse(response);
- return result;
- })
- .catch(async (err: Response) => {
- await handleErrorResponse(err);
- });
- };
- return {
- get: async <T>(url: string, request?: RequestModel): Promise<T> => {
- return handleFetch(url, { ...request, method: 'get' });
- },
- post: async <T>(
- url: string,
- request?: RequestWithBodyModel,
- ): Promise<T> => {
- return handleFetch(url, { ...request, method: 'post' });
- },
- put: async <T>(url: string, request?: RequestWithBodyModel): Promise<T> => {
- return handleFetch(url, { ...request, method: 'put' });
- },
- patch: async <T>(
- url: string,
- request?: RequestWithBodyModel,
- ): Promise<T> => {
- return handleFetch(url, { ...request, method: 'patch' });
- },
- delete: async <T>(url: string, request?: RequestModel): Promise<T> => {
- return handleFetch(url, { ...request, method: 'delete' });
- },
- };
- };
|