From c2c7d3c66be938892edaa77d96d8af7f98a66c6d Mon Sep 17 00:00:00 2001 From: yangyin <1850366751@qq.com> Date: 星期五, 08 十一月 2024 10:57:20 +0800 Subject: [PATCH] 修改样式显示还是隐藏 --- src/utils/request.ts | 285 +++++++++++++++++++++++++++++++-------------------------- 1 files changed, 155 insertions(+), 130 deletions(-) diff --git a/src/utils/request.ts b/src/utils/request.ts index 45df830..666feaf 100644 --- a/src/utils/request.ts +++ b/src/utils/request.ts @@ -1,79 +1,60 @@ -import type { AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosInstance, AxiosRequestConfig, CreateAxiosDefaults } from 'axios'; import axios from 'axios'; import { ElMessage } from 'element-plus'; +import { NO_AUTH_API_LIST } from '../api/ai/chat'; +import { LOGIN_URL, TEL_LOGIN_URL } from '../api/ai/user'; +import { Logger } from '../model/logger/Logger'; +import emitter from './mitt'; +import { debounce, decodeFormData } from './util'; import { AUTH_URL, MAIN_URL, SECONDARY_URL } from '/@/constants'; -import { Local, Session } from '/@/utils/storage'; +import { Local, LoginInfo, Session } from '/@/utils/storage'; // import JSONbig from 'json-bigint'; -//#region ====================== 鍚庣 res.Code ====================== -// // 鎽樿: -// // 鎴愬姛 -// Success = 0, -// // -// // 鎽樿: -// // 纭锛堟潈闄愰獙璇佷娇鐢級 -// Confirm = -1, -// // -// // 鎽樿: -// // 鎻愮ず锛堥獙璇佸け璐ュ悗浣跨敤锛� -// Prompt = -2, -// // -// // 鎽樿: -// // 璀﹀憡锛堜笟鍔″紓甯镐娇鐢級 -// Alert = -3, -// // -// // 鎽樿: -// // 閿欒锛堟湭鎹曡幏绯荤粺寮傚父浣跨敤锛� -// Error = -4, -// // -// // 鎽樿: -// // 瓒呮椂锛堟殏涓嶄娇鐢級 -// TimeOut = -5 +//#region ====================== 鍚庣 res.err_code ====================== +export const enum ErrorCode { + /** @description 鏉冮檺楠岃瘉澶辫触 */ + Message = 'MESSAGE', + /** @description 鍐呴儴閿欒 */ + Exception = 'EXCEPTION', + /** @description 鏃犳潈浣跨敤 */ + Auth = 'AUTH', +} //#endregion -const initRequestInterceptor = (request: AxiosInstance,isAuth=false) => { + +const emitNoAuth = () => { + emitter.emit('logout'); + emitter.emit('openLoginDlg'); +}; + +export const handleNormalAuth = () => { + const accessSession = Local.get(accessSessionKey); + if (!accessSession) { + emitter.emit('logout'); + emitter.emit('openLoginDlg'); + } + return !!accessSession; +}; + +export const handleNoAuth = debounce(() => { + emitNoAuth(); +}); +const initRequestInterceptor = (request: AxiosInstance) => { // 娣诲姞璇锋眰鎷︽埅鍣� request.interceptors.request.use( (config) => { - // // 鍦ㄥ彂閫佽姹備箣鍓嶅仛浜涗粈涔� token - // if (Local.get(accessTokenKey)) { - // (<any>config.headers).common['Authorization'] = `${Session.Local('token')}`; - // } - // 鑾峰彇鏈湴鐨� token - const accessToken = Local.get(accessTokenKey); - if (accessToken) { - // 灏� token 娣诲姞鍒拌姹傛姤鏂囧ご涓�� - if(isAuth){ - config.headers!['Authorization'] = `Bearer ${accessToken}`; - - }else{ - config.headers['Referrer-Policy'] = undefined; - - } - config.headers['hswatersession'] = Local.get('hswatersession'); - - // 鍒ゆ柇 accessToken 鏄惁杩囨湡 - const jwt: any = decryptJWT(accessToken); - const exp = getJWTDate(jwt.exp as number); - const isExpired = new Date() >= exp; - // token 宸茬粡杩囨湡 - if (isExpired) { - // 鑾峰彇鍒锋柊 token - const refreshAccessToken = Local.get(refreshAccessTokenKey); - - // 鎼哄甫鍒锋柊 token - if (refreshAccessToken) { - config.headers!['X-Authorization'] = `Bearer ${refreshAccessToken}`; - } - } - // get璇锋眰鏄犲皠params鍙傛暟 - if (config.method?.toLowerCase() === 'get' && config.data) { - let url = config.url + '?' + tansParams(config.data); - url = url.slice(0, -1); - config.data = {}; - config.url = url; + const accessSession = Local.get(accessSessionKey); + if (accessSession) { + // 灏� token 娣诲姞鍒拌姹傛姤鏂囧ご涓� + config.headers['hswatersession'] = accessSession; + } + if (!NO_AUTH_API_LIST.includes(config.url)) { + if (!accessSession && config.url !== LOGIN_URL && config.url !== TEL_LOGIN_URL) { + handleNoAuth(config.url); + throw '鏉冮檺楠岃瘉澶辫触'; } } + return config; }, (error) => { @@ -87,12 +68,12 @@ (res) => { // 鑾峰彇鐘舵�佺爜鍜岃繑鍥炴暟鎹� const status = res.status; - const serve = res.data; - // code 涓� -1 灏辨槸鏉冮檺楠岃瘉澶辫触 - if (serve?.code === -1) { - clearAccessTokens(); - window.location.reload(); + const serveData = res.data; + if (!serveData) { + ElMessage.error('璇锋眰澶辫触'); + throw new Error('璇锋眰澶辫触'); } + // 澶勭悊 401 if (status === 401) { clearAccessTokens(); @@ -102,56 +83,36 @@ if (status >= 400) { throw new Error(res.statusText || 'Request Error.'); } - // 澶勭悊瑙勮寖鍖栫粨鏋滈敊璇� - if (serve && serve.hasOwnProperty('errors') && serve.errors) { - throw new Error(JSON.stringify(serve.errors || 'Request Error.')); - } - // 璇诲彇鍝嶅簲鎶ユ枃澶� token 淇℃伅 - - // 鍙兘鍙� access-token - const accessToken = res.headers['access-token']; - // 鍙兘鍙� x-access-token' - const refreshAccessToken = res.headers['x-access-token']; - - // 鍒ゆ柇鏄惁鏄棤鏁� token - if (accessToken === 'invalid_token') { - // ElMessage.error('鐧诲綍澶辨晥'); - clearAccessTokens(); - window.location.reload(); - } - // 鍒ゆ柇鏄惁瀛樺湪鍒锋柊 token锛屽鏋滃瓨鍦ㄥ垯瀛樺偍鍦ㄦ湰鍦� - else if (refreshAccessToken && accessToken && accessToken !== 'invalid_token') { - Local.set(accessTokenKey, accessToken); - Local.set(refreshAccessTokenKey, refreshAccessToken); - } - - if (!serve.json_ok && !isAuth) { - // ElMessage.warning(serve.json_msg) - throw new Error('鍝嶅簲閿欒'); - } // 鍝嶅簲鎷︽埅鍙婅嚜瀹氫箟澶勭悊 - if (serve.data === 401) { - clearAccessTokens(); - } else if (serve.code === undefined) { - return Promise.resolve(res.data); - // return res.data; - } else if (serve.code !== 200) { - const message = JSON.stringify(serve.message); - - ElMessage.error(message); - throw new Error(message); + if (!serveData.json_ok) { + switch (serveData?.err_code) { + case ErrorCode.Auth: + if (res.config.url !== LOGIN_URL && res.config.url !== TEL_LOGIN_URL) { + handleNoAuth(); + throw '鏉冮檺楠岃瘉澶辫触'; + } + break; + case ErrorCode.Exception: + const param = res.config.data ? `\n 璇锋眰鍙傛暟锛�${JSON.stringify(decodeFormData(res.config.data))}\n` : ''; + ElMessage.error('鍐呴儴閿欒锛�'); + Logger.error(`${res.config.url} 鍝嶅簲澶辫触${param}`, serveData?.json_msg && new Error(serveData?.json_msg)); + return res.data; + } } return res.data; }, (error) => { + if (typeof error === 'string') { + // ElMessage.error(error); + return Promise.reject(error); + } // 澶勭悊鍝嶅簲閿欒 if (error.response) { if (error.response.status === 401) { clearAccessTokens(); } } - // 瀵瑰搷搴旈敊璇仛鐐逛粈涔� if (error.message.indexOf('timeout') != -1) { ElMessage.error('缃戠粶瓒呮椂'); @@ -167,21 +128,69 @@ ); }; // 閰嶇疆鏂板缓涓�涓� axios 瀹炰緥 -const service = axios.create({ - baseURL: MAIN_URL, - timeout: 50000, - headers: { 'Content-Type': 'application/json;charset=utf-8 ' }, +const createAxiosInstance = (option: Partial<CreateAxiosDefaults<any>> = {}) => { + return axios.create({ + baseURL: MAIN_URL, + timeout: 1200000, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + ...option, + }); +}; +const service = createAxiosInstance(); + +export const mainRequest = service; + +//#region ====================== 娴佸搷搴旀暟鎹� ====================== +const streamInstance = createAxiosInstance({ + adapter: 'fetch', + responseType: 'stream', }); +const decoder = new TextDecoder(); +const readStream = async (stream: ReadableStream, cb: (value) => void): Promise<any> => { + const reader = stream.getReader(); + let lastValue = ''; + const p = new Promise(async (resolve, reject) => { + let fullValue = ''; + while (1) { + const { done, value } = await reader.read(); + if (done) { + break; + } + // const txt = decoder.decode(Uint8Array.from([...lastValue, ...value])); + const txt = decoder.decode(value); + const txtArr = txt.split('\n'); + txtArr[0] = lastValue + txtArr[0]; + txtArr.forEach((value, index, array) => { + // 涓�鑸笉浼氬嚭鐜拌繛缁崲琛岋紝鍙彲鑳芥渶鍚庝竴涓槸鎹㈣ + if (index === array.length - 1) { + lastValue = value; + } else { + const decodeValue = decodeURIComponent(value); + fullValue += decodeValue; + cb(decodeValue); + } + }); + } + resolve(fullValue); + }); + return p; +}; -const authService = axios.create({ - // baseURL: MAIN_URL, - timeout: 50000, - headers: { 'Content-Type': 'application/json;charset=utf-8 ' }, +export const streamReq = async (config: AxiosRequestConfig<any>, callback: (value) => void) => { + const response = await streamInstance(config); + const stream = response as unknown as ReadableStream; + return readStream(stream, (value) => { + const jsonValue = JSON.parse(value); + callback(jsonValue); + }); +}; +//#endregion -}); initRequestInterceptor(service); -initRequestInterceptor(authService,true) +initRequestInterceptor(streamInstance); export function secondaryRequest(config: AxiosRequestConfig<any>) { return service({ @@ -194,7 +203,7 @@ * 鐢ㄤ簬璁块棶鐧诲綍鎺ュ彛 */ export function authRequest(config: AxiosRequestConfig<any>) { - return authService({ + return service({ ...config, baseURL: AUTH_URL, }); @@ -203,27 +212,43 @@ * @description 鍩熷悕鍓嶇紑 * 闃叉绫讳技浜� http://sqi.beng35.com/airp 鍜� http://sqi.beng35.com/test 鍏敤鍚屼竴涓� token 鎴� userInfo */ -const subDomainName = window.location.pathname - .split('/') - .filter((item) => !!item) - .join('-'); -const domainPrefix = subDomainName ? `${subDomainName}-` : ''; +export const getDomainPrefix = (win: Window) => { + const subDomainName = win.location.pathname + .split('/') + .filter((item) => !!item) + .join('-'); + const domainPrefix = subDomainName ? `${subDomainName}-` : ''; + return domainPrefix; +}; + // token 閿畾涔� -export const accessTokenKey = domainPrefix + 'access-token'; -export const refreshAccessTokenKey = `x-${accessTokenKey}`; +export const sessionName = 'access-session'; +export const userName = 'userName'; + +export const getSessionKey = (win: Window) => { + return getDomainPrefix(win) + sessionName; +}; +export const getUserNameKey = (win: Window) => { + return getDomainPrefix(win) + userName; +}; + +export const accessSessionKey = getSessionKey(window); +export const userNameKey = getUserNameKey(window); + +export const refreshAccessTokenKey = `x-${accessSessionKey}`; // userInfo閿畾涔� -export const userInfoKey = domainPrefix + 'userInfo'; +export const userInfoKey = getDomainPrefix(window) + 'userInfo'; // 鑾峰彇 token -export const getToken = () => { - return Local.get(accessTokenKey); +export const getSession = () => { + return Local.get(accessSessionKey); }; // 娓呴櫎 token export const clearAccessTokens = async () => { - Local.remove(accessTokenKey); - Local.remove(refreshAccessTokenKey); + // Local.remove(accessSessionKey); + LoginInfo.remove(); // 娓呴櫎鐢ㄦ埛淇℃伅锛堟瘡娆″埛鏂伴兘闇�瑕佸埄鐢ㄧ敤鎴蜂俊鎭幓璇锋眰瀵瑰簲鏉冮檺鑿滃崟锛� Local.remove(userInfoKey); // 娓呴櫎鍏朵粬 -- Gitblit v1.9.3