24 lines
846 B
TypeScript

/* eslint-disable unicorn/prevent-abbreviations */
export function wrapClientAction<Args extends unknown[], Return>(
fn: (...args: Args) => Promise<{ data?: Return; error?: string; ok: boolean }>,
): (...args: Args) => Promise<Return> {
return async (...args: Args): Promise<Return> => {
const res = await fn(...args);
if (!res.ok) throw new Error(res.error ?? 'Неизвестная ошибка');
return res.data as Return;
};
}
export async function wrapServerAction<T>(
action: () => Promise<T>,
): Promise<{ data: T; ok: true } | { error: string; ok: false }> {
try {
const data = await action();
return { data, ok: true };
} catch (error) {
const message = error instanceof Error ? error.message : 'Неизвестная ошибка сервера';
return { error: message, ok: false };
}
}