12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- import axios, { AxiosRequestConfig } from "axios";
- import { defaultsDeep } from "lodash";
- import { Exception } from "../exception";
- export type RequestConfig = AxiosRequestConfig & {
- interceptors?: { [name: string]: ReturnType<typeof Http["interceptor"]> };
- originBody?: boolean;
- prefix?: string;
- silence?: boolean;
- };
- function createRequest(defReqConfig: RequestConfig) {
- const { interceptors, ...httpConfig } = defReqConfig;
- const http = axios.create(httpConfig);
- Object.values(interceptors || {})?.forEach((item) => {
- item.request && http.interceptors.request.use(item.request);
- item.response && http.interceptors.response.use(item.response);
- });
- return async function (
- url: string,
- config: AxiosRequestConfig & {
- originBody?: boolean;
- prefix?: string;
- silence?: boolean;
- }
- ) {
- const { originBody, prefix, silence, ...thisConfig } = Object.assign(
- {},
- config,
- { url }
- );
- if (prefix) {
- thisConfig.url = prefix + thisConfig.url;
- }
- try {
- let response = (await http(thisConfig)).data;
- if (originBody) {
- response = {
- errorNo: 200,
- errorDesc: "",
- result: response,
- };
- }
- if (response.errorNo !== 200) {
- const silence = config.silence ?? config.method === "GET";
- throw Exception.error({
- msg: response.errorDesc,
- silence,
- result: response,
- });
- }
- return response;
- } catch (error) {
- if (error instanceof Exception) throw error;
- throw Exception.error({ msg: `${error}`, silence, result: error });
- }
- };
- }
- export class Http {
- static config: RequestConfig = {
- timeout: 10000,
- headers: { "Content-Type": "application/json; charset=utf-8" },
- };
- static setConfig(config: RequestConfig) {
- Object.assign(this.config, config);
- }
- static defaultConfig(config: RequestConfig) {
- defaultsDeep(this.config, config);
- }
- static create(config?: RequestConfig) {
- return createRequest(Object.assign({}, this.config, config));
- }
- static interceptor(interceptor: {
- request?: (config: RequestConfig) => RequestConfig;
- response?: <T>(res: T) => T;
- }) {
- return interceptor;
- }
- }
|