Files
call-sdk/packages/common/lib/utils/apiHelper.ts

90 lines
2.0 KiB
TypeScript
Raw Normal View History

2025-01-22 14:44:40 +05:30
import { RequestKeys } from "@universal-call-sdk/adapter-ameyo/lib/types";
import { METHODS, Request, RequestType } from "../types/Request";
2025-01-22 14:44:40 +05:30
const handleError = (context: string, error: unknown): void => {
console.error(`[${context}]`, error);
};
const getFetchResponse = async(
url: string,
method: string,
data: any,
requestType: RequestType,
2025-01-22 14:44:40 +05:30
headers: Record<string, string>
): Promise<any> => {
const fetchOptions: RequestInit = {
method,
headers: {
"Content-Type":
requestType === RequestType.JSON ? "application/json" : "text/plain",
...headers,
},
...(method !== METHODS.GET && { body: data }),
};
2025-01-22 14:44:40 +05:30
try {
const res = await fetch(url, fetchOptions);
2025-01-22 14:44:40 +05:30
if (!res.ok) {
2025-01-22 14:44:40 +05:30
throw new Error(`HTTP error! Status: ${res.status} ${res.statusText}`);
}
const contentType = res.headers.get("Content-Type") || "";
2025-01-22 14:44:40 +05:30
if (contentType.includes("application/json")) {
return await res.json();
2025-01-22 14:44:40 +05:30
} else if (contentType.includes("text/plain")) {
return await res.text();
} else {
throw new Error(`Unsupported Content-Type: ${contentType}`);
}
} catch (err) {
2025-01-22 14:44:40 +05:30
handleError("Fetch error:", err);
return null;
}
};
2025-01-22 14:44:40 +05:30
export const apiHelper = async({
url,
method,
requestKey,
requestType = RequestType.JSON,
2025-01-22 14:44:40 +05:30
headers = {},
data = {},
}: Request) => {
const requestPayload =
requestType === RequestType.RAW ? data : JSON.stringify(data);
2025-01-22 14:44:40 +05:30
try {
2025-01-22 14:44:40 +05:30
if (requestKey === RequestKeys.GET_AGENTS_FOR_CALL_TRANSFER) {
return getFetchResponse(
url,
method,
requestPayload,
requestType,
headers || {}
);
}
const response = await getFetchResponse(
url,
method,
requestPayload,
requestType,
headers || {}
);
2025-01-22 14:44:40 +05:30
return {
data: {
2025-01-22 14:44:40 +05:30
requestKey,
response,
},
};
} catch (error) {
2025-01-22 14:44:40 +05:30
handleError("Response error:", error);
return null;
}
};
2025-01-22 14:44:40 +05:30
export default apiHelper;