refactor: convert wishlist creation from API to form action
This commit is contained in:
@@ -1,4 +1,9 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import type { PageServerLoad, Actions } from './$types';
|
||||
import { db } from '$lib/server/db';
|
||||
import { wishlists } from '$lib/db/schema';
|
||||
import { createId } from '@paralleldrive/cuid2';
|
||||
import { fail } from '@sveltejs/kit';
|
||||
import { wishlistSchema } from '$lib/server/validation';
|
||||
|
||||
export const load: PageServerLoad = async (event) => {
|
||||
const session = await event.locals.auth();
|
||||
@@ -6,3 +11,39 @@ export const load: PageServerLoad = async (event) => {
|
||||
session
|
||||
};
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
createWishlist: async ({ request, locals }) => {
|
||||
const formData = await request.formData();
|
||||
const rawData = Object.fromEntries(formData);
|
||||
|
||||
const result = wishlistSchema.safeParse(rawData);
|
||||
if (!result.success) {
|
||||
return fail(400, { success: false, error: result.error.errors.map(e => e.message).join(', ') });
|
||||
}
|
||||
|
||||
const session = await locals.auth();
|
||||
const userId = session?.user?.id || null;
|
||||
|
||||
const ownerToken = createId();
|
||||
const publicToken = createId();
|
||||
|
||||
const [wishlist] = await db
|
||||
.insert(wishlists)
|
||||
.values({
|
||||
...result.data,
|
||||
ownerToken,
|
||||
publicToken,
|
||||
userId
|
||||
})
|
||||
.returning();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
ownerToken,
|
||||
publicToken,
|
||||
title: wishlist.title,
|
||||
createdAt: wishlist.createdAt
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user