UNPKG

infly-libs

Version:

工具组件库

98 lines (83 loc) 2.63 kB
import axios from "axios"; import Uts from "./Uts.js"; import TokenService from "./TokenService.js"; const baseURL = process.env.VUE_APP_BASE_API; const { env } = Uts.getEnv() || {}; const isTestEnv = Uts.contain(["localhost", "infly-test"], env); const isProdAPI = Uts.contain(["https://api.sutpay.com"], baseURL); /** * 创建封装的 axios 实例 * @param {Object} config 配置项 * @param {Function|String} config.getToken 获取 token 的函数或值 * @param {Function} config.onLogout 登出回调 * @param {Function} config.onNotify 通知回调 * @returns {AxiosInstance} */ export function createService(config) { const { logoutAction = "user/logout", // 退出登录的action方法 onLogout, onNotify } = config || {}; const service = axios.create({ baseURL }); /** * 发送通知 */ const handleNotify = ({ message, type = "error", duration = 5000 }) => { if (Uts.isFunction(onNotify)) { onNotify({ message, type, duration }); } else { console.warn("[Notify]", message); } }; // 涉及到store和request循环依赖,导致store为undefined,所以不要引入store来处理而是通过闭包形式 const handleLogout = () => { if (Uts.isFunction(onLogout)) { onLogout(logoutAction); } }; service.interceptors.request.use( config => { const Token = TokenService.getToken(); if (Token) { config.headers["Authorization"] = " JWT " + Token; } if (isTestEnv && isProdAPI) { handleNotify({ message: `当前环境为测试环境,接口请求为正式环境接口,请暂停操作,检查构建文件`, type: "error", duration: 10 * 1000 }); } return config; }, error => { return Promise.reject(error); } ); service.interceptors.response.use( response => { return response.data || {}; }, error => { const { response } = error || {}; const { status } = response || {}; if ([401, 403].includes(status)) { handleNotify({ message: `登录信息已过期(${status}), 请重新登录!`, type: "error" }); handleLogout(); } else if ([500, 502].includes(status)) { handleNotify({ message: `服务器异常(${status}),请联系开发人员`, type: "error" }); } return Promise.reject(error); } ); return service; } const service = createService(); export default service;