CustomTokenInterceptor.ts 5.82 KB
import { message } from "ant-design-vue";
import { AutumnConfig } from "autumn-vue/lib/core/config/AutumnConfig";
import { DefaultTokenInterceptor } from "autumn-vue/lib/core/http/DefaultTokenInterceptor";
import { AuthenticationManager } from "autumn-vue/lib/core/security/AuthenticationManager";
import { AxiosInstance } from "axios";
import dayjs, { Dayjs } from "dayjs";

export class CustomTokenInterceptor {
	public static readonly AUTHORIZATION = "Authorization";

	constructor(
		public axios: AxiosInstance,
		public authService: AuthenticationManager,
	) {
		// 初始化拦截器
		this.initInterceptors();
	}

	/**
	 * 格式化时间的函数
	 * @param time
	 * @param key
	 */
	formatTime(time: Dayjs, key?: string) {
		// 在这里执行时间格式化操作,使用合适的日期库,例如moment.js、date-fns等
		// 示例:使用date-fns格式化时间
		if (key && key.endsWith("Date")) {
			const formattedTime = time.format("YYYY-MM-DD");
			return formattedTime;
		} else {
			const formattedTime = time.format("YYYY-MM-DD HH:mm");
			return formattedTime;
		}
	}

	/**
	 * 判断对象是否为dayjs类型
	 * @param obj
	 */
	isDayjsObject(obj) {
		return dayjs.isDayjs(obj);
	}

	/**
	 * 递归处理时间字段的函数
	 * @param obj
	 * @param key
	 */
	recursivelyFormatTime(obj, level: number, key?: string) {
		if (level > 5) {
			return obj;
		}
		level++;
		// if (obj instanceof Date) {
		//     // 如果对象是日期类型,格式化它
		//     return this.formatTime(obj);
		// } else
		if (this.isDayjsObject(obj)) {
			return this.formatTime(obj, key);
		} else if (typeof obj === "object") {
			// 如果对象是复杂对象,递归遍历它的属性
			for (const key in obj) {
				/* eslint-disable-next-line  */
				if (obj.hasOwnProperty(key)) {
					obj[key] = this.recursivelyFormatTime(obj[key], level, key);
				}
			}
		}
		return obj;
	}

	/**
	 * 处理请求失败事件
	 * @ param type
	 * @ param msg
	 */
	/**
	 * 处理请求失败事件
	 * @ param type
	 * @ param msg
	 */
	showMessage(type: string, msg: string, status: string): void {
		if (msg) {
			if (type === "error") {
				message.error(msg, 6);
			} else {
				message.warning(msg, 5);
			}
		}
		/* eslint-disable-next-line  */
		if (status == "401") {
			window.location.href = "/login";
		}
	}

	/**
	 * http握手错误
	 * @param error  响应回调,根据不同响应进行不同操作
	 */
	private handleError(error: any) {
		if (!error.response) {
			return;
		}
		console.log(error);
		// 状态码判断
		const status = error.response?.status;
		const errorResponse = error.response?.data;
		const statusText = error.response.statusText;
		let msg;
		let type = "error";
		switch (status) {
			case 0: {
				msg = "无法连接到服务器,请检测您的网络";
				break;
			}
			case 400: {
				msg = "请求错误(400)";
				if (errorResponse) {
					if (typeof errorResponse === "string") {
						msg = errorResponse;
					} else if (typeof errorResponse === "object") {
						msg = errorResponse.message;
					} else {
						msg = statusText;
					}
				}
				break;
			}
			case 401: {
				type = "warning";
				msg = "未授权,请重新登录(401)";
				break;
			}
			case 403: {
				msg = "拒绝访问(403)";
				break;
			}
			case 404: {
				msg = AutumnConfig.ERROR_404_HINT;
				break;
			}
			case 408: {
				msg = "请求超时(408)";
				break;
			}
			case 500: {
				msg = AutumnConfig.ERROR_500_HINT;
				break;
			}
			case 501: {
				msg = "服务未实现(501)";
				break;
			}
			case 502: {
				msg = "网络错误(502)";
				break;
			}
			case 503: {
				msg = "服务不可用(503)";
				break;
			}
			case 504: {
				msg = "网络超时(504)";
				break;
			}
			case 505: {
				msg = "HTTP版本不受支持(505)";
				break;
			}
			default: {
				msg = `连接出错(${status})!`;
			}
		}
		this.showMessage(type, msg, status);
	}

	/**
	 * 初始化拦截器
	 */
	private initInterceptors(): void {
		/**
		 * 请求拦截器
		 * 每次请求前,如果存在token则在请求头中携带token
		 */
		this.axios.interceptors.request.use(
			(config: any) => {
				// 登录流程控制中,根据本地是否存在token判断用户的登录情况
				// 但是即使token存在,也有可能token是过期的,所以在每次的请求头中携带token
				// 后台根据携带的token判断用户的登录情况,并返回给我们对应的状态码
				const authToken = this.authService.getToken();
				if (authToken) {
					config.headers.Authorization = `Bearer ${  authToken}`;
				}
				if (config.method === "post" && config.data) {
					// post请求加上spinning样式,防止重复提交
					/* eslint-disable-next-line  */
					if (config.url.indexOf("/page") === -1) {}
					config.data = this.recursivelyFormatTime(config.data, 0);
				}
				return config;
			},
			(error: any) => {
				this.handleError(error);
				return Promise.reject(error);
			},
		);

		// 响应拦截器
		this.axios.interceptors.response.use(
			// 请求成功
			(res: any) => {
				if (res.status === 200) {
					if (res.headers) {
						const resToken = res.headers[DefaultTokenInterceptor.AUTHORIZATION];
						if (resToken) {
							this.authService.updateToken(resToken);
						}
					}
					return Promise.resolve(res);
				} else {
					this.handleError(res);
					return Promise.reject(res);
				}
			},
			// 请求失败
			(error: any) => {
				if (error) {
					// 请求已发出,但是不在2xx的范围
					this.handleError(error);
					return Promise.reject(error.response);
				} else {
					// 处理断网的情况
					// eg:请求超时或断网时,更新state的network状态
					// network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
					// 关于断网组件中的刷新重新获取数据,会在断网组件中说明
					// this.showMessage('网络连接异常,请稍后再试!');
				}
			},
		);
	}
}