70 lines
2.2 KiB
TypeScript
70 lines
2.2 KiB
TypeScript
import { AxiosError } from 'axios';
|
|
|
|
type ApiErrorPayload = {
|
|
message?: string;
|
|
error?: string;
|
|
status?: string;
|
|
statusCode?: number;
|
|
data?: unknown;
|
|
};
|
|
|
|
export const logGroupRequest = (method: string, url: string, payload?: unknown) => {
|
|
console.log(`[HOOK_API][${method}] URL:`, url);
|
|
console.log(`[HOOK_API][${method}] PAYLOAD:`, payload ?? null);
|
|
};
|
|
|
|
export const logGroupResponse = (method: string, url: string, response: unknown) => {
|
|
const meta = response as { statusCode?: number; status?: string; message?: string };
|
|
console.log(`[HOOK_API][${method}] SUCCESS URL:`, url);
|
|
console.log(`[HOOK_API][${method}] SUCCESS META:`, {
|
|
statusCode: meta?.statusCode ?? null,
|
|
status: meta?.status ?? null,
|
|
message: meta?.message ?? null,
|
|
});
|
|
console.log(`[HOOK_API][${method}] SUCCESS RESPONSE:`, response);
|
|
};
|
|
|
|
export const logGroupError = (method: string, url: string, error: unknown) => {
|
|
const axiosError = error as AxiosError<ApiErrorPayload>;
|
|
console.error(
|
|
`[HOOK_API][${method}] ERROR RESPONSE:`,
|
|
axiosError?.response?.data ?? axiosError?.message ?? error
|
|
);
|
|
};
|
|
|
|
export const getApiErrorMessage = (error: unknown) => {
|
|
const axiosError = error as AxiosError<ApiErrorPayload>;
|
|
const apiMessage =
|
|
axiosError?.response?.data?.message ||
|
|
axiosError?.response?.data?.error ||
|
|
axiosError?.message;
|
|
|
|
return apiMessage || 'An unexpected error occurred';
|
|
};
|
|
|
|
export const normalizeApiError = (error: unknown) => {
|
|
const normalized = new Error(getApiErrorMessage(error));
|
|
(normalized as Error & { originalError?: unknown }).originalError = error;
|
|
return normalized;
|
|
};
|
|
|
|
export const resolveMutationRequest = <T>(resource: string, payload: T) => {
|
|
const rawPayload = payload as unknown as { resource?: string; payload?: unknown };
|
|
const canUseDynamicResource =
|
|
(!resource || resource.trim() === '') &&
|
|
typeof rawPayload?.resource === 'string' &&
|
|
rawPayload.resource.trim() !== '';
|
|
|
|
if (canUseDynamicResource) {
|
|
return {
|
|
url: rawPayload.resource as string,
|
|
body: rawPayload.payload ?? payload,
|
|
};
|
|
}
|
|
|
|
return {
|
|
url: resource,
|
|
body: payload,
|
|
};
|
|
};
|