Skip to content

Commit

Permalink
refactor(http): ♻️ add requestInterceptors
Browse files Browse the repository at this point in the history
  • Loading branch information
G committed May 10, 2024
1 parent f7cf26f commit 259eb07
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
22 changes: 16 additions & 6 deletions packages/apis/https/axios/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { deepMerge } from '@gbeata/utils';
import { deepMerge, getItem } from '@gbeata/utils';
// eslint-disable-next-line import/no-extraneous-dependencies
import { clone } from 'lodash-es';

import { ContentTypeEnum, ResultEnum } from '../enums/httpEnum';
import { ContentTypeEnum, ResultEnum, StorageEnum } from '../enums/httpEnum';
import { GAxios } from './Axios';
import axios from 'axios';

Expand Down Expand Up @@ -35,12 +35,12 @@ const transform: AxiosTransform = {
throw new Error('请求接口错误');
}
// 这里 code,result,message为 后台统一的字段,需要在 types.ts内修改为项目自己的接口返回格式
const { code, result, message } = data;
const { code, message } = data;

// 这里逻辑可以根据项目进行修改
const hasSuccess = data && Reflect.has(data, 'code') && code === ResultEnum.SUCCESS;
if (hasSuccess) {
return result;
return data.data;
}
// 在此处根据自己项目的实际情况对不同的code执行不同的操作
// 如果不希望中断当前请求,请return数据,否则直接抛出异常即可
Expand Down Expand Up @@ -115,14 +115,24 @@ const transform: AxiosTransform = {
// ...
return config;
},
// 请求拦截器处理
requestInterceptors: (config, options) => {
const token = getItem(StorageEnum.Token);
if (token && (config as Recordable).requestOptions?.withToken !== false) {
// 是否携带token
(config as Recordable).headers.Authorization = options.authenticationScheme
? `${options.authenticationScheme} ${token}`
: token;
}
return config;
},
};

function createAxios(options?: Partial<CreateAxiosOptions>) {
console.log(import.meta.env.VITE_PREFIX_URL);
return new GAxios(
deepMerge(
{
authenticationScheme: '',
authenticationScheme: 'Bearer',
timeout: 10 * 1000,
header: { 'Content-Type': ContentTypeEnum.JSON },
transform: clone(transform),
Expand Down
4 changes: 4 additions & 0 deletions packages/apis/https/enums/httpEnum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,7 @@ export enum ContentTypeEnum {
// form-data upload
FORM_DATA = 'multipart/form-data;charset=UTF-8',
}

export enum StorageEnum {
Token = 'token',
}

0 comments on commit 259eb07

Please sign in to comment.