index.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import axios, { AxiosRequestConfig } from "axios";
  2. import { defaultsDeep } from "lodash";
  3. import { Exception } from "../exception";
  4. export type RequestConfig = AxiosRequestConfig & {
  5. interceptors?: { [name: string]: ReturnType<typeof Http["interceptor"]> };
  6. originBody?: boolean;
  7. prefix?: string;
  8. silence?: boolean;
  9. };
  10. function createRequest(defReqConfig: RequestConfig) {
  11. const { interceptors, ...httpConfig } = defReqConfig;
  12. const http = axios.create(httpConfig);
  13. Object.values(interceptors || {})?.forEach((item) => {
  14. item.request && http.interceptors.request.use(item.request);
  15. item.response && http.interceptors.response.use(item.response);
  16. });
  17. return async function (
  18. url: string,
  19. config: AxiosRequestConfig & {
  20. originBody?: boolean;
  21. prefix?: string;
  22. silence?: boolean;
  23. }
  24. ) {
  25. const { originBody, prefix, silence, ...thisConfig } = Object.assign(
  26. {},
  27. config,
  28. { url }
  29. );
  30. if (prefix) {
  31. thisConfig.url = prefix + thisConfig.url;
  32. }
  33. try {
  34. let response = (await http(thisConfig)).data;
  35. if (originBody) {
  36. response = {
  37. errorNo: 200,
  38. errorDesc: "",
  39. result: response,
  40. };
  41. }
  42. if (response.errorNo !== 200) {
  43. const silence = config.silence ?? config.method === "GET";
  44. throw Exception.error({
  45. msg: response.errorDesc,
  46. silence,
  47. result: response,
  48. });
  49. }
  50. return response;
  51. } catch (error) {
  52. if (error instanceof Exception) throw error;
  53. throw Exception.error({ msg: `${error}`, silence, result: error });
  54. }
  55. };
  56. }
  57. export class Http {
  58. static config: RequestConfig = {
  59. timeout: 10000,
  60. headers: { "Content-Type": "application/json; charset=utf-8" },
  61. };
  62. static setConfig(config: RequestConfig) {
  63. Object.assign(this.config, config);
  64. }
  65. static defaultConfig(config: RequestConfig) {
  66. defaultsDeep(this.config, config);
  67. }
  68. static create(config?: RequestConfig) {
  69. return createRequest(Object.assign({}, this.config, config));
  70. }
  71. static interceptor(interceptor: {
  72. request?: (config: RequestConfig) => RequestConfig;
  73. response?: <T>(res: T) => T;
  74. }) {
  75. return interceptor;
  76. }
  77. }