Skip to content

Commit

Permalink
feat: ✨ update, delete user
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinWu098 committed Feb 9, 2024
1 parent 58dd1cd commit c9ef515
Show file tree
Hide file tree
Showing 2 changed files with 108 additions and 0 deletions.
67 changes: 67 additions & 0 deletions src/routes/profile/+page.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { fail, redirect } from "@sveltejs/kit";

import type { Actions, PageServerLoad } from "./$types";

import { prisma } from "$lib/server/prisma";

export const load: PageServerLoad = async (event) => {
const user = event.locals.user;

return user ?? null;
};

export const actions: Actions = {
updateUser: updateUser,
deleteUser: deleteUser,
};

async function updateUser({ request, locals }: { request: Request; locals: App.Locals }) {
const session = await locals.auth.validate();
if (!session) {
throw redirect(302, "/");
}

const { firstName, lastName } = Object.fromEntries(await request.formData()) as {
firstName: string;
lastName: string;
};

try {
await prisma.user.update({
where: {
id: session.user.userId,
},
data: {
firstName: firstName,
lastName: lastName,
},
});
} catch (err) {
console.error(err);
return fail(500, { message: "Could not update user." });
}

return {
status: 200,
};
}

async function deleteUser({ locals }: { locals: App.Locals }) {
const session = await locals.auth.validate();
if (!session) {
throw redirect(302, "/");
}

try {
await prisma.user.delete({
where: {
id: session.user.userId,
},
});
} catch (err) {
console.error(err);
return fail(500, { message: "Could not delete user." });
}

throw redirect(300, "/auth");
}
41 changes: 41 additions & 0 deletions src/routes/profile/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<script lang="ts">
import type { PageData } from "./$types";
import { enhance } from "$app/forms";
export let data: PageData;
$: ({ user } = data);
</script>

<div>
{#if user}
<div>
<p>{user.firstName} {user.lastName}</p>
<div>
<form use:enhance action="/auth/logout" method="post">
<button type="submit" class="btn">
<span>Logout</span>
</button>
</form>
</div>
</div>

<form action="?/updateUser" method="POST">
<h3>Editing: {user.firstName} {user.lastName} {user.userId}</h3>

<input type="text" id="firstName" name="firstName" value={user.firstName} />
<input type="text" id="lastName" name="lastName" value={user.lastName} />

<button type="submit">Update Profile</button>
</form>

<form action="?/deleteUser" method="POST">
<button type="submit" class="secondary outline">Delete Account</button>
</form>
{:else}
<div>
<p>You are not signed in. Please sign in.</p>
<a href="/auth">Sign In</a>
</div>
{/if}
</div>

0 comments on commit c9ef515

Please sign in to comment.