import type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'; export type ContentType = | 'application/json' | 'application/octet-stream' | 'application/x-www-form-urlencoded' | 'multipart/form-data' | 'text/html' | 'text/plain'; export interface RequestOption { /** * The hook to check backend response is success or not * * @param response Axios response */ isBackendSuccess: (response: AxiosResponse) => boolean; /** * The hook after backend request fail * * For example: You can handle the expired token in this hook * * @param response Axios response * @param instance Axios instance */ onBackendFail: ( response: AxiosResponse, instance: AxiosInstance ) => Promise | Promise; /** * The hook to handle error * * For example: You can show error message in this hook * * @param error */ onError: (error: AxiosError) => void | Promise; /** * The hook before request * * For example: You can add header token in this hook * * @param config Axios config */ onRequest: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig | Promise; /** * transform backend response when the responseType is json * * @param response Axios response */ transformBackendResponse(response: AxiosResponse): any | Promise; } interface ResponseMap { arrayBuffer: ArrayBuffer; blob: Blob; document: Document; stream: ReadableStream; text: string; } export type ResponseType = keyof ResponseMap | 'json'; export type MappedType = R extends keyof ResponseMap ? ResponseMap[R] : JsonType; export type CustomAxiosRequestConfig = Omit & { responseType?: R; }; export interface RequestInstanceCommon { /** * cancel all request * * if the request provide abort controller sign from config, it will not collect in the abort controller map */ cancelAllRequest: () => void; /** * cancel the request by request id * * if the request provide abort controller sign from config, it will not collect in the abort controller map * * @param requestId */ cancelRequest: (requestId: string) => void; /** you can set custom state in the request instance */ state: T; } /** The request instance */ export interface RequestInstance> extends RequestInstanceCommon { (config: CustomAxiosRequestConfig): Promise>; } export type FlatResponseSuccessData = { data: T; error: null; response: AxiosResponse; }; export type FlatResponseFailData = { data: null; error: AxiosError; response: AxiosResponse; }; export type FlatResponseData = | FlatResponseSuccessData | FlatResponseFailData; export interface FlatRequestInstance, ResponseData = any> extends RequestInstanceCommon { ( config: CustomAxiosRequestConfig ): Promise, ResponseData>>; }