81 lines
1.9 KiB
TypeScript
81 lines
1.9 KiB
TypeScript
|
|
// frontend/dashboard/src/utils/apiHelpers.ts
|
||
|
|
/**
|
||
|
|
* Utility functions for API operations
|
||
|
|
*/
|
||
|
|
|
||
|
|
export function formatApiError(error: any): string {
|
||
|
|
if (error?.detail) {
|
||
|
|
return error.detail;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (error?.message) {
|
||
|
|
return error.message;
|
||
|
|
}
|
||
|
|
|
||
|
|
return 'An unexpected error occurred';
|
||
|
|
}
|
||
|
|
|
||
|
|
export function isApiError(error: any): boolean {
|
||
|
|
return error && (error.detail || error.error_code);
|
||
|
|
}
|
||
|
|
|
||
|
|
export function formatDate(date: Date | string): string {
|
||
|
|
const d = typeof date === 'string' ? new Date(date) : date;
|
||
|
|
return d.toISOString().split('T')[0];
|
||
|
|
}
|
||
|
|
|
||
|
|
export function formatDateTime(date: Date | string): string {
|
||
|
|
const d = typeof date === 'string' ? new Date(date) : date;
|
||
|
|
return d.toISOString();
|
||
|
|
}
|
||
|
|
|
||
|
|
export function buildQueryParams(params: Record<string, any>): URLSearchParams {
|
||
|
|
const searchParams = new URLSearchParams();
|
||
|
|
|
||
|
|
Object.entries(params).forEach(([key, value]) => {
|
||
|
|
if (value !== null && value !== undefined && value !== '') {
|
||
|
|
if (Array.isArray(value)) {
|
||
|
|
value.forEach(item => searchParams.append(key, String(item)));
|
||
|
|
} else {
|
||
|
|
searchParams.append(key, String(value));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
return searchParams;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function debounce<T extends (...args: any[]) => any>(
|
||
|
|
func: T,
|
||
|
|
wait: number
|
||
|
|
): (...args: Parameters<T>) => void {
|
||
|
|
let timeout: NodeJS.Timeout | null = null;
|
||
|
|
|
||
|
|
return (...args: Parameters<T>) => {
|
||
|
|
if (timeout) {
|
||
|
|
clearTimeout(timeout);
|
||
|
|
}
|
||
|
|
|
||
|
|
timeout = setTimeout(() => {
|
||
|
|
func.apply(null, args);
|
||
|
|
}, wait);
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
export function retryWithDelay<T>(
|
||
|
|
fn: () => Promise<T>,
|
||
|
|
retries: number = 3,
|
||
|
|
delay: number = 1000
|
||
|
|
): Promise<T> {
|
||
|
|
return fn().catch((error) => {
|
||
|
|
if (retries > 0) {
|
||
|
|
return new Promise((resolve) => {
|
||
|
|
setTimeout(() => {
|
||
|
|
resolve(retryWithDelay(fn, retries - 1, delay * 2));
|
||
|
|
}, delay);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
throw error;
|
||
|
|
});
|
||
|
|
}
|