import { Subject } from "rxjs"; export interface BaseResponse { success: boolean; code: string; msg: string; data: T; } type HttpReqParam = { url: string; method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE"; params?: Record; encode?: "form" | "json"; // 入参编码类型 headers?: Record; }; export type ApiException = "invalidToken" | "serverError"; const exceptionSub = new Subject(); export const exceptionOb = exceptionSub.asObservable(); function extHandle(res: BaseResponse) { if (res.code === "A0230") { // 访问令牌无效或已过期 exceptionSub.next("invalidToken"); } return { ...res, success: res.code === "00000", }; } export default async function httpRequest({ url, method = "GET", params = {}, encode = "json", headers = {} }: HttpReqParam) { const token = sessionStorage.getItem("token"); if (token) { headers = { Authorization: token, ...headers }; } if (method === "GET") { const query = urlEncode(params); const _url = query ? url + "?" + query : url; const res = await fetch(_url, { headers }); return res.json().then(res => extHandle(res) as T); } else { const body = encode === "json" ? JSON.stringify(params) : urlEncode(params); const _headers = encode === "json" ? { "Content-Type": "application/json; charset=utf-8", ...headers } : { "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", ...headers }; const res = await fetch(url, { method, headers: _headers, body }); return res.json().then(res => extHandle(res) as T); } } export function urlEncode(params?: Record) { let query = ""; if (params && Object.keys(params).length > 0) { const qs = []; for (let attr in params) { qs.push(`${attr}=${encodeURIComponent(params[attr])}`); } query = qs.join("&"); } return query; }