import { FORBIDDEN, PARSE_ERROR, SUCCESS } from '$lib/server/commonResponses'; import { devices, groups } from '$lib/server/db'; import { redirect, type Actions, type ServerLoad } from '@sveltejs/kit'; import { decode } from 'decode-formdata'; import { z } from 'zod'; export const load: ServerLoad = async ({ locals: { guard }, params }) => { guard.requiresAdmin().orRedirects(); const group = await groups.getById(params.id ?? ''); if (!group && params.id !== 'new') { redirect(302, '/dash/groups'); } return { devices: await devices.getAll(), group, }; }; export const actions = { update: async ({ request, locals: { guard }, params }) => { if (guard.requiresAdmin().isFailed()) return FORBIDDEN; const schema = z.object({ name: z .string({ message: 'Name is required.' }) .min(3, { message: 'Name must be at least 3 characters.' }) .max(24, { message: 'Name must be at most 24 characters.' }), devices: z.array(z.string()), }); const parsed = schema.safeParse( decode(await request.formData(), { arrays: ['devices'], }), ); if (!parsed.success) { return PARSE_ERROR(parsed.error); } const err = params.id === 'new' ? await groups.create({ ...parsed.data }) : await groups.update({ id: params.id ?? '', ...parsed.data }); return err ? err.toFail() : SUCCESS; }, delete: async ({ locals: { guard }, params }) => { if (guard.requiresAdmin().isFailed()) return FORBIDDEN; const err = await groups.delete(params.id ?? ''); return err ? err.toFail() : SUCCESS; }, } satisfies Actions;