diff --git a/web/src/lib/fetch-action.ts b/web/src/lib/fetch-action.ts new file mode 100644 index 0000000..9db9619 --- /dev/null +++ b/web/src/lib/fetch-action.ts @@ -0,0 +1,25 @@ +export interface Request extends Omit { + action?: string; + form?: Record; +} + +export default function fetchAction(request: Request): Promise { + return fetch(request.action ?? '/', { + ...request, + method: request.method ?? 'GET', + headers: { + ...request.headers, + 'X-Sveltekit-Action': 'true', + }, + body: request.form ? createFormData(request.form) : request.body || undefined, + }); +} + +function createFormData(data: Record): FormData { + const form = new FormData(); + for (const key in data) { + if (typeof data[key] !== 'string') continue; + form.set(key, data[key]); + } + return form; +}