87 lines
2.1 KiB
TypeScript
87 lines
2.1 KiB
TypeScript
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
|
|
import {
|
|
AnalyticsEventNameConstants,
|
|
NETWORK_ERROR,
|
|
} from "../App/common/constants";
|
|
import { sendAsAnalyticsEvent } from "../App/common/hooks/useAnalyticsEvent";
|
|
import { NetworkConnectorModule } from "../App/common/native-module/NativeModules";
|
|
import { BASE_URL } from "./NetworkConstant";
|
|
|
|
export const getDefaultHeaderData = async () => {
|
|
try {
|
|
const data = await NetworkConnectorModule.getAllNativeHeaders();
|
|
return data;
|
|
} catch (error) {
|
|
sendAsAnalyticsEvent({
|
|
name: AnalyticsEventNameConstants.HI_RN_FETCH_NATIVE_HEADER_ERROR,
|
|
properties: {
|
|
reason: error?.toString() || NETWORK_ERROR,
|
|
},
|
|
});
|
|
return null;
|
|
}
|
|
};
|
|
|
|
export const getXTargetHeaderInfo = (
|
|
moduleName: string,
|
|
): AxiosRequestConfig => {
|
|
return {
|
|
headers: {
|
|
"X-Target": moduleName,
|
|
},
|
|
};
|
|
};
|
|
|
|
export const getAcceptHeaderInfo = (acceptType: string): AxiosRequestConfig => {
|
|
return {
|
|
decompress: true,
|
|
headers: {
|
|
"Accept-Encoding": acceptType,
|
|
},
|
|
};
|
|
};
|
|
|
|
export const ApiClient = axios.create({
|
|
baseURL: BASE_URL,
|
|
timeout: 10000,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
});
|
|
|
|
class DetailAxiosError extends Error {
|
|
axiosCode?: string;
|
|
statusCode?: number;
|
|
|
|
constructor(message: string, axiosCode?: string, statusCode?: number) {
|
|
super(message);
|
|
this.axiosCode = axiosCode;
|
|
this.statusCode = statusCode;
|
|
}
|
|
}
|
|
|
|
export const handleSuccess = <T>(response: AxiosResponse<T>): T => {
|
|
return response.data;
|
|
};
|
|
|
|
export const handleError = (error: unknown): never => {
|
|
if (axios.isAxiosError(error)) {
|
|
if (error.response) {
|
|
throw new DetailAxiosError(
|
|
`Request failed with status code: ${error.response.status} `,
|
|
error.code,
|
|
error.response.status,
|
|
);
|
|
} else if (error.request) {
|
|
throw new DetailAxiosError(
|
|
"No response received from the server",
|
|
error.code,
|
|
);
|
|
} else {
|
|
throw new DetailAxiosError("Error setting up the request", error.code);
|
|
}
|
|
} else {
|
|
throw new Error("Unknown error occurred");
|
|
}
|
|
};
|