Files
call-sdk/packages/common/lib/utils/getResponse.ts
2025-01-20 15:48:25 +05:30

85 lines
1.8 KiB
TypeScript

import { METHODS, Request, RequestType } from "../types/Request";
const getFetchResponse = async (
url: string,
method: string,
data: any,
requestType: RequestType,
headers: any
) => {
const fetchOptions = {
method,
headers: {
"Content-Type":
requestType === RequestType.JSON ? "application/json" : "text/plain",
...headers,
},
...(method !== METHODS.GET && { body: data }),
};
try {
const res = await fetch(url, fetchOptions);
if (!res.ok) {
return { error: res };
}
const contentType = res.headers.get("Content-Type") || "";
if (
requestType === RequestType.JSON &&
contentType.includes("application/json")
) {
return await res.json();
} else if (
contentType.includes("text/plain") &&
requestType == RequestType.RAW
) {
return await res.text();
} else {
throw new Error(`Unsupported Content-Type: ${contentType}`);
}
} catch (err) {
console.error("Response is not a valid JSON or text", err);
return { error: "Failed to parse response" };
}
};
export const getResponse = async ({
url,
method,
requestKey,
requestType = RequestType.JSON,
headers = null,
data = {},
}: Request) => {
const requestPayload =
requestType === RequestType.RAW ? data : JSON.stringify(data);
try {
const response = await getFetchResponse(
url,
method,
requestPayload,
requestType,
headers || {}
);
if (response?.error) {
console.error(response.error);
return {
data: {
requestKey: requestKey,
response: response,
},
};
}
return {
data: {
requestKey: requestKey,
response: response,
},
};
} catch (error) {
console.error("Fetch error:", error);
throw error;
}
};
export default getResponse;