| | |
| | | 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, LoginInfo, Session } from '/@/utils/storage'; |
| | | import { Logger } from '../model/logger/Logger'; |
| | | // import JSONbig from 'json-bigint'; |
| | | |
| | | //#region ====================== 后端 res.err_code ====================== |
| | |
| | | ); |
| | | }; |
| | | // 配置新建一个 axios 实例 |
| | | const createAxiosInstance = () => { |
| | | const createAxiosInstance = (option: Partial<CreateAxiosDefaults<any>> = {}) => { |
| | | return axios.create({ |
| | | baseURL: MAIN_URL, |
| | | timeout: 50000, |
| | | headers: { 'Content-Type': 'application/json;charset=utf-8 ' }, |
| | | ...option, |
| | | }); |
| | | }; |
| | | |
| | | const service = createAxiosInstance(); |
| | | |
| | | export const mainRequest = service; |
| | | |
| | | //#region ====================== 流响应数据 ====================== |
| | | const streamInstance = createAxiosInstance({ |
| | | adapter: 'fetch', |
| | | responseType: 'stream', |
| | | }); |
| | | const decoder = new TextDecoder(); |
| | | const encoder = new TextEncoder(); |
| | | const readStream = async (stream: ReadableStream, cb: (value) => void) => { |
| | | const reader = stream.getReader(); |
| | | let lastValue = new Uint8Array(); |
| | | while (1) { |
| | | const { done, value } = await reader.read(); |
| | | if (done) { |
| | | break; |
| | | } |
| | | const txt = decoder.decode(Uint8Array.from([...lastValue, ...value])); |
| | | const txtArr = txt.split('\n'); |
| | | txtArr.forEach((value, index, array) => { |
| | | // 一般不会出现连续换行,只可能最后一个是换行 |
| | | if (index === array.length - 1) { |
| | | // 编码回去,中文切分会乱码 |
| | | lastValue = encoder.encode(value); |
| | | } else { |
| | | cb(value); |
| | | } |
| | | }); |
| | | } |
| | | }; |
| | | |
| | | export const streamReq = (config: AxiosRequestConfig<any>, callback: (value) => void) => { |
| | | streamInstance(config).then((response) => { |
| | | const stream = response as unknown as ReadableStream; |
| | | readStream(stream, (value) => { |
| | | const jsonValue = JSON.parse(value); |
| | | callback(jsonValue); |
| | | }); |
| | | }); |
| | | }; |
| | | //#endregion |
| | | |
| | | initRequestInterceptor(service); |
| | | initRequestInterceptor(streamInstance); |
| | | |
| | | export function secondaryRequest(config: AxiosRequestConfig<any>) { |
| | | return service({ |