Skip to content

Commit

Permalink
feat(projects): 请求拦截器添加刷新token
Browse files Browse the repository at this point in the history
  • Loading branch information
Soybean committed Jan 12, 2022
1 parent 09c7658 commit 839b82b
Show file tree
Hide file tree
Showing 8 changed files with 213 additions and 126 deletions.
29 changes: 29 additions & 0 deletions mock/api/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,35 @@ const apis: MockMethod[] = [
}
};
}
},
{
url: '/mock/testToken',
method: 'post',
response: (option: any): Service.BackendServiceResult<true | null> => {
if (option.headers?.authorization !== token.token) {
return {
code: 66666,
message: 'token 失效',
data: null
};
}
return {
code: 200,
message: 'ok',
data: true
};
}
},
{
url: '/mock/updateToken',
method: 'post',
response: (): Service.BackendServiceResult<string> => {
return {
code: 200,
message: 'ok',
data: token.token
};
}
}
];

Expand Down
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"scripts": {
"dev": "cross-env VITE_HTTP_ENV=test vite",
"dev:prod": "cross-env VITE_HTTP_ENV=prod vite",
"typecheck": "vue-tsc --noEmit",
"typecheck": "vue-tsc",
"build": "npm run typecheck && cross-env VITE_HTTP_ENV=prod vite build",
"build:test": "npm run typecheck && cross-env VITE_HTTP_ENV=test vite build",
"build:vercel": "npm run typecheck && cross-env VITE_HTTP_ENV=prod VITE_IS_VERCEL=1 vite build",
Expand All @@ -31,17 +31,17 @@
"dayjs": "^1.10.7",
"form-data": "^4.0.0",
"lodash-es": "^4.17.21",
"naive-ui": "^2.23.2",
"naive-ui": "^2.24.1",
"pinia": "^2.0.9",
"qs": "^6.10.2",
"qs": "^6.10.3",
"vue": "^3.2.26",
"vue-router": "^4.0.12"
},
"devDependencies": {
"@commitlint/cli": "^16.0.2",
"@commitlint/config-conventional": "^16.0.0",
"@iconify/json": "^1.1.454",
"@iconify/vue": "^3.1.1",
"@iconify/json": "^1.1.455",
"@iconify/vue": "^3.1.2",
"@types/crypto-js": "^4.1.0",
"@types/node": "^17.0.8",
"@types/qs": "^6.9.7",
Expand Down
245 changes: 127 additions & 118 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions src/config/common/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,6 @@ export const ERROR_STATUS = {

/** 不弹出错误信息的code */
export const NO_ERROR_MSG_CODE: (string | number)[] = [];

/** token失效需要刷新token的接口 */
export const REFRESH_TOKEN_CODE: (string | number)[] = [66666];
8 changes: 8 additions & 0 deletions src/service/api/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,11 @@ export function fetchUserInfo() {
export function fetchUserRoutes(userId: string = 'soybean') {
return mockRequest.post<ApiRoute.Route>('/getUserRoutes', { userId });
}

export function fetchTestToken() {
return mockRequest.post('/testToken', { userName: 'Soybean' });
}

export function fetchUpdateToken(refreshToken: string) {
return mockRequest.post('/updateToken', { refreshToken });
}
26 changes: 26 additions & 0 deletions src/service/request/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type { AxiosRequestConfig } from 'axios';
import { useAuthStore } from '@/store';
import { getRefreshToken, setToken, setRefreshToken } from '@/utils';
import { fetchUpdateToken } from '../api';

/**
* 刷新token
* token失效时的请求配置
*/
export async function refreshToken(axiosConfig: AxiosRequestConfig) {
const { resetAuthStore } = useAuthStore();
const refreshToken = getRefreshToken();
const { data } = await fetchUpdateToken(refreshToken);
if (data) {
setToken(data.token);
setRefreshToken(data.refreshToken);
const config = { ...axiosConfig };
if (config.headers) {
config.headers.Authorization = data.token;
}
return config;
}

resetAuthStore(true);
return null;
}
15 changes: 13 additions & 2 deletions src/service/request/instance.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from 'axios';
import type { AxiosRequestConfig, AxiosInstance, AxiosError, CancelTokenStatic } from 'axios';
import { REQUEST_TIMEOUT } from '@/config';
import { REQUEST_TIMEOUT, REFRESH_TOKEN_CODE } from '@/config';
import {
getToken,
transformRequestData,
Expand All @@ -9,6 +9,7 @@ import {
handleBackendError,
handleServiceResult
} from '@/utils';
import { refreshToken } from './helpers';

/**
* 封装axios请求类
Expand Down Expand Up @@ -51,13 +52,23 @@ export default class CustomAxiosInstance {
}
);
this.instance.interceptors.response.use(
response => {
async response => {
const { status } = response;
if (status === 200 || status < 300 || status === 304) {
const backend = response.data as Service.BackendServiceResult;
// 请求成功
if (backend.code === this.backendSuccessCode) {
return handleServiceResult(null, backend.data);
}

// token失效, 刷新token
if (REFRESH_TOKEN_CODE.includes(backend.code)) {
const config = await refreshToken(response.config);
if (config) {
return this.instance.request(config);
}
}

const error = handleBackendError(backend);
return handleServiceResult(error, null);
}
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"~/*": ["./*"]
},
"lib": ["esnext", "dom", "dom.iterable", "scripthost"],
"skipLibCheck": true
"skipLibCheck": true,
"noEmit": true
},
"include": ["vite.config.*", "src/typings/*.d.ts", "src/**/*", "src/**/*.vue", "mock/**/*.ts", "build/**/*.ts", ".env-config.ts"],
"exclude": ["/dist/**", "node_modules"]
Expand Down

0 comments on commit 839b82b

Please sign in to comment.