Files
famdone/frontend/src/lib/forms.ts
T
2026-08-24 18:09:44 +01:00

39 lines
1.3 KiB
TypeScript

import { goto } from '$app/navigation';
/**
* Resolve-callback factory for `use:enhance`.
*
* Follows `result.type === 'redirect'` automatically (actions like login,
* billing portal, and logged-out pricing choose throw redirects), then hands
* everything else to the optional handler — falling back to the default
* `update()` when none is given.
*
* Usage:
* <form method="POST" use:enhance={handleResult(({ result }) => {...})}>
* <form method="POST" use:enhance={handleResult()}>
*/
export function handleResult(
handler?: (ctx: { result: any; update: () => Promise<void> }) => Promise<void>
) {
return async ({ result, update }: any) => {
if (result?.type === 'redirect') {
const target = String(result.location);
const isExternal = /^https?:\/\//i.test(target) && !target.startsWith(window.location.origin);
if (isExternal) {
window.location.assign(target);
} else {
await goto(target);
}
return;
}
if (result?.type === 'error') {
// Unhandled server exception — never let these vanish silently.
const { notices } = await import('$lib/stores/notices.svelte');
notices.error('Something went wrong', result.error?.message || 'Internal error.');
return;
}
if (handler) await handler({ result, update });
else await update();
};
}