diff --git a/Webserver/src/lib/client/httpRequests.ts b/Webserver/src/lib/client/httpRequests.ts new file mode 100644 index 0000000..a805045 --- /dev/null +++ b/Webserver/src/lib/client/httpRequests.ts @@ -0,0 +1,23 @@ +import type { APIResponse } from '$lib/interfaces'; + +export async function redirectAPI({ form, fdata }: { form?: HTMLFormElement; fdata?: FormData }) { + if (!fdata && form) fdata = new FormData(form); + else if (!fdata) throw new Error('No formdata provided!'); + + // Get endpoint, prefer form, then formdata or empty + const endpoint = (form?.dataset.endpoint ?? fdata.get('endpoint')) ?? ''; + // Append endpoint to formdata + if (!fdata?.has('endpoint')) + fdata.append('endpoint', endpoint); + + // Send request to be redirected to given endpoint + const response = await fetch('/api/redirect', { + method: 'POST', + body: fdata! + }); + + // Await respose from webserver + const mdata = (await response.json()) as APIResponse; + // Basic error handling + if (!mdata.success) alert(`Error while processing '${endpoint}'!`); +} diff --git a/Webserver/src/routes/admin/+page.svelte b/Webserver/src/routes/admin/+page.svelte index ecd1e4f..b98b382 100644 --- a/Webserver/src/routes/admin/+page.svelte +++ b/Webserver/src/routes/admin/+page.svelte @@ -8,6 +8,7 @@ import { rgbToHex, type Color, getContrastColor } from '$lib/client/color'; import { detectGamepad, gamepadButtonPress } from '$lib/client/gamepad'; import { initializeMatrix, type Matrix } from '$lib/client/matrix'; + import { redirectAPI } from '$lib/client/httpRequests'; import { toRadians } from '$lib/client/miscellaneous'; import type { APIResponse } from '$lib/interfaces'; import { onMount } from 'svelte'; @@ -56,17 +57,8 @@ // break; } - // Append endpoint to formdata for redirection - fdata.append('endpoint', form.dataset.endpoint ?? ''); - // Send request to be redirected to given endpoint - const response = await fetch('/api/redirect', { - method: 'POST', - body: fdata - }); - // Await respose from webserver - const mdata = (await response.json()) as APIResponse; - // Basic error handling - if (!mdata.success) alert(`Error while processing '${form.dataset.endpoint}'!`); + // Redirect data over local endpoint + await redirectAPI({ form, fdata }); } // function displayText(formData: FormData) {} @@ -253,7 +245,7 @@