63 lines
1.7 KiB
TypeScript
63 lines
1.7 KiB
TypeScript
import { API_URL } from "$env/static/private";
|
|
import { fail, redirect, type Actions } from "@sveltejs/kit";
|
|
import type { PageServerLoad } from "./$types";
|
|
|
|
import { superValidate } from "sveltekit-superforms";
|
|
import { zod } from "sveltekit-superforms/adapters";
|
|
|
|
import { handleRedirect } from "$lib/utils";
|
|
import { groupSchema } from "$lib/validations/group";
|
|
|
|
export const load: PageServerLoad = async ({ url, params: { chapterId }, locals: { user } }) => {
|
|
|
|
if (!user) redirect(302, handleRedirect('login', url));
|
|
|
|
if (user.groups.find(g => g.chapter === parseInt(chapterId))) {
|
|
redirect(302, `/chapters/${chapterId}/groups`);
|
|
}
|
|
|
|
const form = await superValidate(zod(groupSchema));
|
|
|
|
return {
|
|
title: 'Nouveau groupe',
|
|
form
|
|
};
|
|
};
|
|
|
|
export const actions: Actions = {
|
|
default: async ({ url, locals: { user }, fetch, request, params: { chapterId } }) => {
|
|
|
|
if (!user) redirect(302, handleRedirect('login', url));
|
|
|
|
if (!chapterId) redirect(302, '/chapters');
|
|
|
|
const form = await superValidate(request, zod(groupSchema));
|
|
|
|
if (!form.valid) {
|
|
return fail(400, { form });
|
|
}
|
|
|
|
const res = await fetch(`${API_URL}/groupCreate`, {
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
...form.data,
|
|
chapter: parseInt(chapterId)
|
|
})
|
|
});
|
|
|
|
if (!res.ok) {
|
|
|
|
if (res.status === 403) {
|
|
form.errors.name = ["Vous êtes déjà dans un groupe"];
|
|
} else if (res.status === 423) {
|
|
form.errors.name = ["Vous ne pouvez plus créer de groupe"];
|
|
} else {
|
|
form.errors.name = ["Une erreur est survenue, veuillez réessayer plus tard"];
|
|
}
|
|
|
|
return fail(400, { form });
|
|
}
|
|
|
|
redirect(302, `/chapters/${chapterId}/groups`);
|
|
}
|
|
};
|