import type { PageServerLoad } from './$types'; import { error, fail, isRedirect, redirect, type Actions } from '@sveltejs/kit'; import { prisma } from '$lib/db'; import { serverFormatPhoneNumber } from '$lib/utils'; // Tell the page what to do when it loads export const load: PageServerLoad = async ({ locals }) => { // If locals.user doesn't exist (i.e., undefined), then the user is not logged in, \ // i.e, not authenticated nor authorized! We skip the database check early and also // solve a problem with Prisma in case of having an undefined locals.user.id. if (!locals.user?.id) { throw error(403, 'not authorized'); } const user = await prisma.user.findUnique({ where: { id: locals.user.id } }); return { user }; }; export const actions: Actions = { default: async ({ request }) => { const data = await request.formData(); const userID = data.get('userId') as string; const firstName = data.get('firstName') as string; const lastName = data.get('lastName') as string; const phoneNumber = serverFormatPhoneNumber(data.get('phoneNumber') as string); try { const profile = await prisma.profile.create({ data: { userId: userID, firstName: firstName, lastName: lastName, phoneNumber: phoneNumber } }); if (profile) { console.log(`created profile: ${JSON.stringify(profile)}`); throw redirect(303, '/dashboard'); } else { return fail(400); } } catch (err) { if (isRedirect(err)) { throw err; } console.log(err); throw error(400, 'bad request'); } } };