基质喷涂
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

  1. import { Subject } from "rxjs";
  2. export interface BaseResponse<T = unknown> {
  3. success: boolean;
  4. code: string;
  5. msg: string;
  6. data: T;
  7. }
  8. type HttpReqParam = {
  9. url: string;
  10. method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
  11. params?: Record<string, any>;
  12. encode?: "form" | "json"; // 入参编码类型
  13. headers?: Record<string, any>;
  14. };
  15. export type ApiException = "invalidToken" | "serverError";
  16. const exceptionSub = new Subject<ApiException>();
  17. export const exceptionOb = exceptionSub.asObservable();
  18. function extHandle(res: BaseResponse) {
  19. if (res.code === "A0230") {
  20. // 访问令牌无效或已过期
  21. exceptionSub.next("invalidToken");
  22. }
  23. return {
  24. ...res,
  25. success: res.code === "00000",
  26. };
  27. }
  28. export default async function httpRequest<T>({ url, method = "GET", params = {}, encode = "json", headers = {} }: HttpReqParam) {
  29. const token = sessionStorage.getItem("token");
  30. if (token) {
  31. headers = { Authorization: token, ...headers };
  32. }
  33. if (method === "GET") {
  34. const query = urlEncode(params);
  35. const _url = query ? url + "?" + query : url;
  36. const res = await fetch(_url, { headers });
  37. return res.json().then(res => extHandle(res) as T);
  38. } else {
  39. const body = encode === "json" ? JSON.stringify(params) : urlEncode(params);
  40. const _headers =
  41. encode === "json"
  42. ? { "Content-Type": "application/json; charset=utf-8", ...headers }
  43. : { "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", ...headers };
  44. const res = await fetch(url, { method, headers: _headers, body });
  45. return res.json().then(res => extHandle(res) as T);
  46. }
  47. }
  48. export function urlEncode(params?: Record<string, any>) {
  49. let query = "";
  50. if (params && Object.keys(params).length > 0) {
  51. const qs = [];
  52. for (let attr in params) {
  53. qs.push(`${attr}=${encodeURIComponent(params[attr])}`);
  54. }
  55. query = qs.join("&");
  56. }
  57. return query;
  58. }