diff --git a/src/routes/account/+page.server.ts b/src/routes/account/+page.server.ts index 5f1050b..373de7c 100644 --- a/src/routes/account/+page.server.ts +++ b/src/routes/account/+page.server.ts @@ -1,6 +1,7 @@ import { fail, redirect } from '@sveltejs/kit'; import type { Actions, PageServerLoad } from './$types'; +import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'; export const load: PageServerLoad = async ({ locals: { authReq } }) => { const session = await authReq.validate(); @@ -11,6 +12,43 @@ export const load: PageServerLoad = async ({ locals: { authReq } }) => { }; export const actions: Actions = { + updateAccount: async ({ request, locals: { auth, authReq } }) => { + const session = await authReq.validate(); + if (!session) return fail(401); + + const formData = await request.formData(); + const username = formData.get('username') as string; + + // Attempty to update username + // + // Fails if wanted new username is already assigned to another user + try { + await auth.updateUserAttributes(session.user.userId, { + username + }); + } catch (err) { + if (err instanceof PrismaClientKnownRequestError && err.code === 'P2002') { + return fail(400, { + type: 'updateAccount', + message: 'User with username already exists.', + success: false + }); + } + + console.log(err); + return fail(500, { + message: 'Internal server error, please try again later.' + }); + } + + return { + type: 'updateAccount', + message: 'Account updated.', + success: true, + username + }; + }, + signout: async ({ locals: { auth, authReq } }) => { const session = await authReq.validate(); if (!session) return fail(401); diff --git a/src/routes/account/+page.svelte b/src/routes/account/+page.svelte index 5484b3d..2a23d6d 100644 --- a/src/routes/account/+page.svelte +++ b/src/routes/account/+page.svelte @@ -18,7 +18,7 @@

Account

-
+ {#if form?.type === 'updateAccount'} {form?.message} {/if}