基质喷涂
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

64 lines
1.8 KiB

import { Subject } from "rxjs";
export interface BaseResponse<T = unknown> {
success: boolean;
code: string;
msg: string;
data: T;
}
type HttpReqParam = {
url: string;
method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
params?: Record<string, any>;
encode?: "form" | "json"; // 入参编码类型
headers?: Record<string, any>;
};
export type ApiException = "invalidToken" | "serverError";
const exceptionSub = new Subject<ApiException>();
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<T>({ 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<string, any>) {
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;
}