Skip to content

Modern Docker Management, Designed for Everyone

4.9 KB
Raw Blame
import { error as kitError } from '@sveltejs/kit';
import { toast } from 'svelte-sonner';

import { APIError, extractServerMessage, isSessionCancelledError } from '#lib/services/api-service.js';
import type { Result } from '#lib/types/result.js';
import { tryCatch } from '#lib/utils/try-catch.js';

// --- API error extraction ---

export function extractApiErrorMessage(error: any): string {
	if (!error) return 'Unknown error';

	const respData = error?.response?.data;
	const serverMsg = extractServerMessage(respData, true);
	if (serverMsg) return serverMsg;

	const bodyMsg = extractServerMessage(error?.body, true);
	if (bodyMsg) return bodyMsg;

	for (const key of ['error', 'reason', 'stderr', 'data', 'message']) {
		const value = error?.[key];
		if (typeof value === 'string' && value.trim()) return value;
	}

	try {
		return JSON.stringify(error);
	} catch {
		return 'Unknown error';
	}
}

/**
 * Shows a toast for a failed upgrade, avoiding double-wrapping when the extracted
 * message is already the localized "upgrade failed" string. The localized message
 * factory is passed in so this utility stays free of paraglide imports.
 */
export function toastUpgradeError(error: unknown, formatFailed: (args: { error: string }) => string): void {
	const errorMessage = extractApiErrorMessage(error);
	const wrappedPrefix = formatFailed({ error: '' });
	toast.error(errorMessage.startsWith(wrappedPrefix) ? errorMessage : formatFailed({ error: errorMessage }));
}

export async function handleApiResultWithCallbacks<T>({
	result,
	message,
	setLoadingState = () => {},
	onSuccess = async () => {},
	onError = async () => {}
}: {
	result: Result<T, Error>;
	message: string;
	setLoadingState?: (value: boolean) => void;
	onSuccess?: (data: T) => void | Promise<void>;
	onError?: (error: Error) => void | Promise<void>;
}) {
	try {
		setLoadingState(true);

		// Work from a signed-out session is dropped without feedback.
		if (isSessionCancelledError(result.error)) return;
		if (result.error) {
			console.error(`API Error: ${message}:`, result.error);
			if (!(result.error instanceof APIError) || result.error.status !== 403) {
				toast.error(message, { description: extractApiErrorMessage(result.error) });
			}
			await Promise.resolve(onError(result.error));
		} else {
			await Promise.resolve(onSuccess(result.data as T));
		}
	} finally {
		try {
			setLoadingState(false);
		} catch (e) {
			console.warn('Failed to clear loading state', e);
		}
	}
}

// --- Page load error helpers ---

function extractApiErrorStatus(err: unknown, fallbackStatus = 500): number {
	if (err && typeof err === 'object') {
		const maybeResponse = (err as { response?: { status?: unknown } }).response;
		const responseStatus = maybeResponse?.status;
		if (typeof responseStatus === 'number' && Number.isFinite(responseStatus)) {
			return responseStatus;
		}
	}

	if (err && typeof err === 'object') {
		const maybeStatus = (err as { status?: unknown }).status;
		if (typeof maybeStatus === 'number' && Number.isFinite(maybeStatus)) {
			return maybeStatus;
		}
		if (typeof maybeStatus === 'string') {
			const parsed = Number.parseInt(maybeStatus, 10);
			if (!Number.isNaN(parsed)) {
				return parsed;
			}
		}
	}

	return fallbackStatus;
}

/** True when the server explicitly rejected the caller's credentials (401/403). */
export function isAuthRejectionError(err: unknown): boolean {
	const status = extractApiErrorStatus(err, 0);
	return status === 401 || status === 403;
}

export function throwPageLoadError(err: unknown, fallbackMessage: string): never {
	const status = extractApiErrorStatus(err);
	const message = extractApiErrorMessage(err) || fallbackMessage;
	kitError(status, message);
}

// --- Refresh helpers ---

export interface RefreshTask<T> {
	fetch: () => Promise<T>;
	onSuccess: (data: T) => void;
	errorMessage: string;
}

export async function parallelRefresh<T extends Record<string, RefreshTask<any>>>(
	tasks: T,
	setLoading: (loading: boolean) => void
): Promise<void> {
	setLoading(true);

	const taskKeys = Object.keys(tasks);
	const completionStatus = Object.fromEntries(taskKeys.map((k) => [k, true]));

	const updateLoading = (key: string, value: boolean) => {
		completionStatus[key] = value;
		const stillLoading = Object.values(completionStatus).some((v) => v);
		setLoading(stillLoading);
	};

	await Promise.all(
		taskKeys.map(async (key) => {
			const task = tasks[key as keyof T];
			if (!task) return;

			await handleApiResultWithCallbacks({
				result: await tryCatch(task.fetch()),
				message: task.errorMessage,
				setLoadingState: (value) => updateLoading(key, value),
				onSuccess: task.onSuccess
			});
		})
	);
}

export async function simpleRefresh<T>(
	fetch: () => Promise<T>,
	onSuccess: (data: T) => void,
	errorMessage: string,
	setLoading: (loading: boolean) => void
): Promise<void> {
	setLoading(true);
	await handleApiResultWithCallbacks({
		result: await tryCatch(fetch()),
		message: errorMessage,
		setLoadingState: setLoading,
		onSuccess
	});
}