68 lines
2.1 KiB
TypeScript
68 lines
2.1 KiB
TypeScript
import axios, { AxiosRequestConfig } from "axios";
|
|
import { Alert, ToastAndroid } from "react-native";
|
|
import * as Keychain from "react-native-keychain";
|
|
|
|
/**
|
|
* Generic API call function with proper error handling and optional auth.
|
|
* @param url - API endpoint
|
|
* @param method - HTTP method: GET, POST, PUT, DELETE
|
|
* @param data - Request body for POST/PUT
|
|
* @param config - Optional Axios config (headers, params, etc.)
|
|
*/
|
|
export async function apiCall<T>(
|
|
url: string,
|
|
method: "GET" | "POST" | "PUT" | "DELETE" = "GET",
|
|
data?: any,
|
|
config?: AxiosRequestConfig,
|
|
responseErrorMessage?:string
|
|
): Promise<T | null > {
|
|
try {
|
|
// Get saved credentials from Keychain
|
|
const creds = await Keychain.getGenericPassword();
|
|
console.log("Keychain Credentials Found:", creds); // Log if creds were found
|
|
|
|
const headers = {
|
|
"Content-Type": "application/json",
|
|
...(creds ? { Authorization: `Bearer ${creds.password}` } : {}),
|
|
...config?.headers,
|
|
};
|
|
|
|
const response = await axios({
|
|
url,
|
|
method,
|
|
data,
|
|
...config,
|
|
headers,
|
|
});
|
|
|
|
// --- Response Logging ---
|
|
console.log(`--- API Response:${url}///// [${response}] `);
|
|
|
|
return response.data;
|
|
} catch (error: any) {
|
|
if (error.response) {
|
|
// Server responded with a status other than 2xx
|
|
// console.error(
|
|
// "API Error:",
|
|
// `Status: ${error.response.status}`,
|
|
// `Data: ${JSON.stringify(error.response.data)}`
|
|
// );
|
|
if(error.response.status === 400){
|
|
console.log("API Error:9090", url);
|
|
ToastAndroid.show(error.response.data.message || responseErrorMessage, ToastAndroid.SHORT)
|
|
}
|
|
|
|
} else if (error.request) {
|
|
// Request was made but no response received
|
|
// console.error("API Error: No response received", error.request);
|
|
} else {
|
|
// Something else went wrong while setting up the request
|
|
// console.error("API Error:", error);
|
|
}
|
|
console.log(`API : ${url} API Error:`, error);
|
|
return error.response.status
|
|
// Re-throw the error so that the calling function can handle it if needed
|
|
throw error;
|
|
}
|
|
}
|