Adding APIs for different actions to consume down the line in refactor.

This commit is contained in:
Bradley Shellnut 2023-07-18 14:23:45 -07:00
parent 4a803998c6
commit b6b9c36466
26 changed files with 1125 additions and 617 deletions

View file

@ -22,21 +22,21 @@
"seed": "ts-node --esm prisma/seed.ts"
},
"devDependencies": {
"@playwright/test": "^1.35.1",
"@playwright/test": "^1.36.1",
"@sveltejs/adapter-auto": "^1.0.3",
"@sveltejs/adapter-vercel": "^1.0.6",
"@sveltejs/kit": "^1.21.0",
"@sveltejs/kit": "^1.22.3",
"@types/cookie": "^0.5.1",
"@types/node": "^18.16.19",
"@typescript-eslint/eslint-plugin": "^5.60.1",
"@typescript-eslint/parser": "^5.60.1",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"autoprefixer": "^10.4.14",
"eslint": "^8.44.0",
"eslint": "^8.45.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-svelte": "^2.32.2",
"just-clone": "^6.2.0",
"just-debounce-it": "^3.2.0",
"postcss": "^8.4.24",
"postcss": "^8.4.26",
"postcss-import": "^15.1.0",
"postcss-load-config": "^4.0.1",
"postcss-preset-env": "^8.5.1",
@ -47,12 +47,12 @@
"svelte": "^3.59.2",
"svelte-check": "^2.10.3",
"svelte-preprocess": "^5.0.4",
"sveltekit-superforms": "^1.1.3",
"tailwindcss": "^3.3.2",
"sveltekit-superforms": "^1.3.0",
"tailwindcss": "^3.3.3",
"ts-node": "^10.9.1",
"tslib": "^2.6.0",
"typescript": "^4.9.5",
"vite": "^4.3.9",
"vite": "^4.4.4",
"vitest": "^0.25.3",
"zod": "^3.21.4"
},
@ -65,7 +65,7 @@
"@axiomhq/axiom-node": "^0.12.0",
"@fontsource/fira-mono": "^4.5.10",
"@iconify-icons/line-md": "^1.2.23",
"@iconify-icons/mdi": "^1.2.46",
"@iconify-icons/mdi": "^1.2.47",
"@leveluptuts/svelte-side-menu": "^1.0.5",
"@leveluptuts/svelte-toy": "^2.0.3",
"@lucia-auth/adapter-mysql": "^1.1.1",
@ -88,8 +88,8 @@
"svelte-lazy-loader": "^1.0.0",
"svelte-legos": "^0.2.1",
"sveltekit-flash-message": "^0.11.3",
"tailwind-merge": "^1.13.2",
"tailwind-merge": "^1.14.0",
"tailwindcss-animate": "^1.0.6",
"zod-to-json-schema": "^3.21.3"
"zod-to-json-schema": "^3.21.4"
}
}

File diff suppressed because it is too large Load diff

View file

@ -91,9 +91,9 @@ model Collection {
model CollectionItem {
id String @id @default(cuid())
collection_id String
collection_id String @unique
collection Collection @relation(references: [id], fields: [collection_id], onDelete: Cascade)
game_id String
game_id String @unique
game Game @relation(references: [id], fields: [game_id])
times_played Int
@ -104,7 +104,7 @@ model CollectionItem {
model Wishlist {
id String @id @default(cuid())
name String
user_id String
user_id String @unique
auth_user AuthUser @relation(references: [id], fields: [user_id])
items WishlistItem[]
@ -114,9 +114,9 @@ model Wishlist {
model WishlistItem {
id String @id @default(cuid())
wishlist_id String
wishlist_id String @unique
wishlist Wishlist @relation(references: [id], fields: [wishlist_id], onDelete: Cascade)
game_id String
game_id String @unique
game Game @relation(references: [id], fields: [game_id])
created_at DateTime @default(now()) @db.Timestamp(6)
updated_at DateTime @updatedAt @db.Timestamp(6)
@ -184,7 +184,7 @@ model Publisher {
primary_publisher Game[] @relation("PrimaryPublishers")
created_at DateTime @default(now()) @db.Timestamp(6)
updated_at DateTime @updatedAt @db.Timestamp(6)
@@fulltext([name])
@@map("publishers")
}

2
src/app.d.ts vendored
View file

@ -4,7 +4,7 @@
import type { AuthUser } from '@prisma/client';
type User = Omit<AuthUser, 'id' | 'created_at' | 'updated_at'>;
type User = Omit<AuthUser, 'created_at' | 'updated_at'>;
// src/app.d.ts
declare global {

View file

@ -4,6 +4,7 @@
import { fade } from 'svelte/transition';
import plusCircle from '@iconify-icons/line-md/plus-circle';
import minusCircle from '@iconify-icons/line-md/minus-circle';
import { superForm } from 'sveltekit-superforms/client';
// import Button from '$lib/components/button/index.svelte';
import type { GameType, SavedGameType } from '$lib/types';
import { collectionStore } from '$lib/stores/collectionStore';
@ -15,10 +16,16 @@
import { convertToSavedGame } from '$lib/util/gameMapper';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '$components/ui/card';
import { Button } from '$components/ui/button';
import type { SuperValidated } from 'sveltekit-superforms';
import type { ListGameSchema } from '$lib/zodValidation';
import type { CollectionItem } from '@prisma/client';
export let game: GameType | SavedGameType;
export let data: SuperValidated<ListGameSchema>;
export let game: GameType | CollectionItem;
export let detailed: boolean = false;
const { form, errors, enhance, delayed } = superForm(data);
const dispatch = createEventDispatcher();
function removeGameFromWishlist() {
@ -70,8 +77,10 @@
// }
// }
$: existsInCollection = $collectionStore.find((item: SavedGameType) => item.id === game.id);
$: existsInWishlist = $wishlistStore.find((item: SavedGameType) => item.id === game.id);
// $: existsInCollection = $collectionStore.find((item: SavedGameType) => item.id === game.id);
// $: existsInWishlist = $wishlistStore.find((item: SavedGameType) => item.id === game.id);
$: existsInCollection = game.in_collection;
$: existsInWishlist = game.in_wishlist;
$: collectionText = existsInCollection ? 'Remove from collection' : 'Add to collection';
$: wishlistText = existsInWishlist ? 'Remove from wishlist' : 'Add to wishlist';
</script>
@ -79,43 +88,55 @@
<article class="grid grid-template-cols-2 gap-4" transition:fade>
<Card>
<CardHeader>
<CardTitle>{game.name}</CardTitle>
<!-- <CardDescription>Card Description</CardDescription> -->
<CardTitle>{game.game_name}</CardTitle>
</CardHeader>
<CardContent>
<img src={game.thumb_url} alt={`Image of ${game.name}`} loading="lazy" decoding="async" />
<div class="game-details">
{#if game?.players}
<p>Players: {game.players}</p>
<p>Time: {game.playtime} minutes</p>
{#if isGameType(game) && game?.min_age}
<p>Min Age: {game.min_age}</p>
{/if}
{#if detailed && isGameType(game) && game?.description}
<div class="description">{@html game.description}</div>
{/if}
{/if}
</div>
<a
class="thumbnail"
href={`/game/${game.game_id}`}
title={`View ${game.game_name}`}
data-sveltekit-preload-data
>
<img src={game.thumb_url} alt={`Image of ${game.game_name}`} loading="lazy" decoding="async" />
<div class="game-details">
{#if game?.players}
<p>Players: {game.players}</p>
<p>Time: {game.playtime} minutes</p>
{#if isGameType(game) && game?.min_age}
<p>Min Age: {game.min_age}</p>
{/if}
{#if detailed && isGameType(game) && game?.description}
<div class="description">{@html game.description}</div>
{/if}
{/if}
</div>
</a>
</CardContent>
<CardFooter>
<div class="flex gap-2">
<Button variant={existsInCollection ? 'destructive' : 'default'} on:click={onCollectionClick}>
{collectionText}
{#if existsInCollection}
<iconify-icon class="ml-2" icon={minusCircle} width="24" height="24" />
{:else}
<iconify-icon class="ml-2" icon={plusCircle} width="24" height="24" />
{/if}
</Button>
<Button variant={existsInCollection ? 'destructive' : 'default'} on:click={onWishlistClick}>
{wishlistText}
{#if existsInWishlist}
<iconify-icon class="ml-2" icon={minusCircle} width="24" height="24" />
{:else}
<iconify-icon class="ml-2" icon={plusCircle} width="24" height="24" />
{/if}
</Button>
</div>
<div class="grid gap-2 place-items-center">
<form method="POST" use:enhance action={`/collection?/${existsInCollection ? 'remove' : 'add'}`}>
<input type="hidden" name="id" value={game.id} />
<Button variant={existsInCollection ? 'destructive' : 'default'} on:click={onCollectionClick}>
{collectionText}
{#if existsInCollection}
<iconify-icon class="ml-2" icon={minusCircle} width="24" height="24" />
{:else}
<iconify-icon class="ml-2" icon={plusCircle} width="24" height="24" />
{/if}
</Button>
</form>
<form method="POST" use:enhance action={`/wishlist?/${existsInWishlist ? 'remove' : 'add'}`}>
<input type="hidden" name="id" value={game.id} />
<Button variant={existsInWishlist ? 'destructive' : 'default'} on:click={onWishlistClick}>
{wishlistText}
{#if existsInWishlist}
<iconify-icon class="ml-2" icon={minusCircle} width="24" height="24" />
{:else}
<iconify-icon class="ml-2" icon={plusCircle} width="24" height="24" />
{/if}
</Button>
</form>
</div>
</CardFooter>
</Card>
</article>

View file

@ -6,7 +6,6 @@
import logo from './bored-game.png';
export let user: any;
console.log('User', user);
</script>
<header>

View file

@ -18,22 +18,20 @@
// import SkeletonPlaceholder from '../../SkeletonPlaceholder.svelte';
import RemoveCollectionDialog from '../../dialog/RemoveCollectionDialog.svelte';
import RemoveWishlistDialog from '../../dialog/RemoveWishlistDialog.svelte';
import type { SearchSchema } from '$lib/zodValidation';
import type { ListGameSchema, SearchSchema } from '$lib/zodValidation';
interface RemoveGameEvent extends Event {
detail: GameType | SavedGameType;
}
export let data: SuperValidated<SearchSchema>;
const { form, constraints, errors } = superForm(data, {
onSubmit: () => {
boredState.update((n) => ({ ...n, loading: true }));
},
});
export let data;
console.log("text search data", data);
export let showButton: boolean = false;
export let advancedSearch: boolean = false;
const { form, errors, enhance, constraints, message }: SuperValidated<SearchSchema> = superForm(data.form);
const { form: modifyListForm, errors: listErrors, constraints: listConstraints, enhance: listEnhance, message: listMessage } : SuperValidated<ListGameSchema> = superForm(data.modifyListForm);
let gameToRemove: GameType | SavedGameType;
let numberOfGameSkeleton = 1;
let submitButton: HTMLElement;
@ -58,11 +56,11 @@
numberOfGameSkeleton = 1;
}
let placeholderList = [...Array(numberOfGameSkeleton).keys()];
// let placeholderList = [...Array(numberOfGameSkeleton).keys()];
if (form?.error) {
disclosureOpen = true;
}
// if (form?.error) {
// disclosureOpen = true;
// }
async function handleNextPageEvent(event: CustomEvent) {
if (+event?.detail?.page === page + 1) {
@ -87,53 +85,53 @@
submitButton.click();
}
function handleRemoveCollection(event: RemoveGameEvent) {
gameToRemove = event?.detail;
boredState.update((n) => ({
...n,
dialog: { isOpen: true, content: RemoveCollectionDialog, additionalData: gameToRemove }
}));
}
// function handleRemoveCollection(event: RemoveGameEvent) {
// gameToRemove = event?.detail;
// boredState.update((n) => ({
// ...n,
// dialog: { isOpen: true, content: RemoveCollectionDialog, additionalData: gameToRemove }
// }));
// }
function handleRemoveWishlist(event: RemoveGameEvent) {
gameToRemove = event?.detail;
boredState.update((n) => ({
...n,
dialog: { isOpen: true, content: RemoveWishlistDialog, additionalData: gameToRemove }
}));
}
// function handleRemoveWishlist(event: RemoveGameEvent) {
// gameToRemove = event?.detail;
// boredState.update((n) => ({
// ...n,
// dialog: { isOpen: true, content: RemoveWishlistDialog, additionalData: gameToRemove }
// }));
// }
const submitSearch: SubmitFunction = ({ form, data, action, cancel }) => {
const { name } = Object.fromEntries(data);
if (!disclosureOpen && name?.length === 0) {
toast.send('Please enter a search term', {
duration: 3000,
type: ToastType.ERROR,
dismissible: true
});
cancel();
return;
}
// const submitSearch: SubmitFunction = ({ form, data, action, cancel }) => {
// const { name } = Object.fromEntries(data);
// if (!disclosureOpen && name?.length === 0) {
// toast.send('Please enter a search term', {
// duration: 3000,
// type: ToastType.ERROR,
// dismissible: true
// });
// cancel();
// return;
// }
gameStore.removeAll();
boredState.update((n) => ({ ...n, loading: true }));
return async ({ result }) => {
boredState.update((n) => ({ ...n, loading: false }));
// `result` is an `ActionResult` object
if (result.type === 'error') {
toast.send('Error!', { duration: 3000, type: ToastType.ERROR, dismissible: true });
await applyAction(result);
} else if (result.type === 'success') {
gameStore.removeAll();
gameStore.addAll(result?.data?.searchData?.games);
totalItems = result?.data?.searchData?.totalCount;
// toast.send('Success!', { duration: 3000, type: ToastType.INFO, dismissible: true });
await applyAction(result);
} else {
await applyAction(result);
}
};
};
// gameStore.removeAll();
// boredState.update((n) => ({ ...n, loading: true }));
// return async ({ result }) => {
// boredState.update((n) => ({ ...n, loading: false }));
// // `result` is an `ActionResult` object
// if (result.type === 'error') {
// toast.send('Error!', { duration: 3000, type: ToastType.ERROR, dismissible: true });
// await applyAction(result);
// } else if (result.type === 'success') {
// gameStore.removeAll();
// gameStore.addAll(result?.data?.searchData?.games);
// totalItems = result?.data?.searchData?.totalCount;
// // toast.send('Success!', { duration: 3000, type: ToastType.INFO, dismissible: true });
// await applyAction(result);
// } else {
// await applyAction(result);
// }
// };
// };
const dev = process.env.NODE_ENV !== 'production';
@ -226,11 +224,7 @@
<div class="games-list">
{#if $gameStore?.length > 0}
{#each $gameStore as game (game.id)}
<Game
on:handleRemoveWishlist={handleRemoveWishlist}
on:handleRemoveCollection={handleRemoveCollection}
{game}
/>
<Game {game} data={modifyListForm} />
{/each}
{:else}
<h2>Sorry no games found!</h2>

View file

@ -0,0 +1,17 @@
<script lang="ts">
import { Avatar as AvatarPrimitive } from "radix-svelte";
import { cn } from "$lib/utils";
let className: string | undefined | null = undefined;
export { className as class };
</script>
<AvatarPrimitive.Root
class={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
)}
{...$$restProps}
>
<slot />
</AvatarPrimitive.Root>

View file

@ -0,0 +1,17 @@
<script lang="ts">
import { Avatar as AvatarPrimitive } from "radix-svelte";
import { cn } from "$lib/utils";
let className: string | undefined | null = undefined;
export { className as class };
</script>
<AvatarPrimitive.Fallback
class={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
)}
{...$$restProps}
>
<slot />
</AvatarPrimitive.Fallback>

View file

@ -0,0 +1,17 @@
<script lang="ts">
import type { AvatarImageProps } from "radix-svelte";
import { Avatar as AvatarPrimitive } from "radix-svelte";
import { cn } from "$lib/utils";
let className: string | undefined | null = undefined;
export let src: AvatarImageProps["src"] = undefined;
export let alt: AvatarImageProps["alt"] = undefined;
export { className as class };
</script>
<AvatarPrimitive.Image
{alt}
{src}
class={cn("aspect-square h-full w-full", className)}
{...$$restProps}
/>

View file

@ -0,0 +1,3 @@
export { default as Avatar } from "./Avatar.svelte";
export { default as AvatarFallback } from "./AvatarFallback.svelte";
export { default as AvatarImage } from "./AvatarImage.svelte";

View file

@ -1,5 +1,23 @@
import { z } from 'zod';
export type ListGame = {
id: string;
game_name: string;
game_id: string;
collection_id: string;
wishlist_id: string;
times_played: number;
thumb_url: string | null;
in_collection: boolean;
in_wishlist: boolean;
};
export const modifyListGameSchema = z.object({
id: z.string()
});
export type ModifyListGame = typeof modifyListGameSchema;
export const userSchema = z.object({
firstName: z.string().trim().optional(),
lastName: z.string().trim().optional(),

View file

@ -1,5 +1,20 @@
import { Prisma } from '@prisma/client';
import type { SvelteComponent } from 'svelte';
export const gameInclude = Prisma.validator<Prisma.CollectionItemInclude>()({
game: {
select: {
id: true,
name: true,
thumb_url: true
}
}
});
export type CollectionItemWithGame = Prisma.CollectionItemGetPayload<{
include: typeof gameInclude;
}>;
export type Dialog = {
isOpen: boolean;
content?: typeof SvelteComponent;
@ -57,6 +72,15 @@ export type SavedGameType = {
includeInRandom: boolean;
};
export type ListGameType = {
id: string;
game_id: string;
collection_id: string | undefined;
wishlist_id: string | undefined;
times_played: number;
thumb_url: string;
};
export type MechanicType = {
id: string;
};

View file

@ -36,6 +36,20 @@ function IntegerString<schema extends ZodNumber | ZodOptional<ZodNumber>>(schema
);
}
const Search = z.object({
q: z.string().trim().optional().default(''),
minAge: IntegerString(z.number().min(1).max(120).optional()),
minPlayers: IntegerString(z.number().min(1).max(50).optional()),
maxPlayers: IntegerString(z.number().min(1).max(50).optional()),
exactMinAge: z.preprocess((a) => Boolean(a), z.boolean().optional()),
exactMinPlayers: z.preprocess((a) => Boolean(a), z.boolean().optional()),
exactMaxPlayers: z.preprocess((a) => Boolean(a), z.boolean().optional()),
sort: z.enum(['asc', 'desc']).optional(),
sortBy: z.enum(['name', 'min_players', 'max_players', 'min_age', 'times_played']).optional(),
limit: z.number().min(10).max(100).default(10),
skip: z.number().min(0).default(0)
});
export const search_schema = z
.object({
q: z.string().trim().optional().default(''),
@ -45,6 +59,8 @@ export const search_schema = z
exactMinAge: z.preprocess((a) => Boolean(a), z.boolean().optional()),
exactMinPlayers: z.preprocess((a) => Boolean(a), z.boolean().optional()),
exactMaxPlayers: z.preprocess((a) => Boolean(a), z.boolean().optional()),
sort: z.enum(['asc', 'desc']).optional(),
sortBy: z.enum(['name', 'min_players', 'max_players', 'min_age', 'times_played']).optional(),
limit: z.number().min(10).max(100).default(10),
skip: z.number().min(0).default(0)
})
@ -92,6 +108,12 @@ export const search_schema = z
export type SearchSchema = typeof search_schema;
export const collection_search_schema = Search.extend({
collection_id: z.string()
});
export type CollectionSearchSchema = typeof collection_search_schema;
export const search_result_schema = z.object({
client_id: z.string(),
limit: z.number(),

View file

View file

@ -0,0 +1,74 @@
import { error, json } from '@sveltejs/kit';
import prisma from '$lib/prisma.js';
import type { CollectionItemWithGame } from '$lib/types.js';
// Search a user's collection
export async function GET({ url, locals, params }) {
const searchParams = Object.fromEntries(url.searchParams);
const q = searchParams?.q || '';
const limit = parseInt(searchParams?.limit) || 10;
const skip = parseInt(searchParams?.skip) || 0;
const order = searchParams?.order || 'asc';
const sort = searchParams?.sort || 'name';
const collection_id = params.id;
const session = await locals.auth.validate();
console.log('url', url);
console.log('username', locals?.user?.id);
if (!session) {
throw error(401, { message: 'Unauthorized' });
}
let collection = await prisma.collection.findUnique({
where: {
user_id: locals.user.id
}
});
console.log('collection', collection);
if (!collection) {
console.log('Collection was not found');
throw error(404, { message: 'Collection was not found' });
}
try {
const orderBy = { [sort]: order };
let collection_items: CollectionItemWithGame[] = await prisma.collectionItem.findMany({
where: {
collection_id,
AND: [
{
game: {
name: {
contains: q
}
}
}
]
},
orderBy: [
{
game: {
...orderBy
}
}
],
include: {
game: {
select: {
id: true,
name: true,
thumb_url: true
}
}
},
skip,
take: limit
});
return json(collection_items);
} catch (e) {
console.error(e);
throw error(500, { message: 'Something went wrong' });
}
}

View file

View file

@ -0,0 +1,58 @@
import { error, json } from '@sveltejs/kit';
import { Prisma } from '@prisma/client';
import z from 'zod';
import prisma from '$lib/prisma.js';
import { superValidate } from 'sveltekit-superforms/server';
import { search_schema } from '$lib/zodValidation.js';
// Search a user's collection
export const GET = async ({ url, locals, params, request }) => {
try {
z.parse;
} catch (e) {
console.error(e);
return error(500, { message: 'Something went wrong' });
}
const searchParams = Object.fromEntries(url.searchParams);
const q = searchParams?.q || '';
const limit = parseInt(searchParams?.limit) || 10;
const skip = parseInt(searchParams?.skip) || 0;
const order: Prisma.SortOrder = searchParams?.order || 'asc';
const sort = searchParams?.sort || 'name';
const session = await locals.auth.validate();
console.log('url', url);
console.log('username', locals?.user?.id);
try {
const orderBy = { [sort]: order };
let games = await prisma.game.findMany({
where: {
name: {
contains: q
}
},
orderBy: [
{
...orderBy
}
],
select: {
id: true,
name: true,
thumb_url: true
},
skip,
take: limit
});
if (!games) {
throw error(404, { message: 'No games found' });
}
return json(games);
} catch (e) {
console.error(e);
throw error(500, { message: 'Something went wrong' });
}
};

View file

@ -48,6 +48,32 @@ export const actions = {
}
}
});
if (user) {
await prisma.collection.upsert({
where: {
user_id: user.id
},
create: {
user_id: user.id
},
update: {
user_id: user.id
}
});
await prisma.wishlist.upsert({
where: {
user_id: user.id
},
create: {
user_id: user.id,
name: 'My Wishlist'
},
update: {
user_id: user.id,
name: 'My Wishlist'
}
});
}
} catch (e) {
// TODO: need to return error message to the client
console.error(e);

View file

@ -3,6 +3,7 @@ import { setError, superValidate } from 'sveltekit-superforms/server';
import { auth } from '$lib/server/lucia';
import { userSchema } from '$lib/config/zod-schemas';
import { add_user_to_role } from '$db/roles';
import prisma from '$lib/prisma.js';
const signUpSchema = userSchema
.pick({
@ -73,6 +74,17 @@ export const actions = {
}
});
add_user_to_role(user.id, 'user');
await prisma.collection.create({
data: {
user_id: user.id
}
});
await prisma.wishlist.create({
data: {
user_id: user.id,
name: 'My Wishlist'
}
});
console.log('User', user);

View file

@ -32,9 +32,7 @@ import { userSchema } from '$lib/config/zod-schemas.js';
Signup for an account
</h2>
<Label for="firstName">First Name</Label>
<Input
type="text"
id="firstName" class={$errors.firstName && "outline outline-destructive"} name="firstName" placeholder="First Name" autocomplete="given-name" data-invalid={$errors.firstName} bind:value={$form.firstName} />
<Input type="text" id="firstName" class={$errors.firstName && "outline outline-destructive"} name="firstName" placeholder="First Name" autocomplete="given-name" data-invalid={$errors.firstName} bind:value={$form.firstName} />
{#if $errors.firstName}
<p class="text-sm text-destructive">{$errors.firstName}</p>
{/if}

View file

@ -1,65 +1,207 @@
// import { redirect } from '@sveltejs/kit';
// import { superValidate } from 'sveltekit-superforms/server';
// import { search_schema } from '$lib/zodValidation';
import { fail, redirect } from '@sveltejs/kit';
import { setError, superValidate } from 'sveltekit-superforms/server';
import type { PageServerLoad } from '../$types.js';
import prisma from '$lib/prisma.js';
import { modifyListGameSchema, type ListGame } from '$lib/config/zod-schemas.js';
import type { CollectionItemWithGame } from '$lib/types.js';
import { search_schema } from '$lib/zodValidation.js';
export const load = async ({ fetch, url, locals }) => {
// const session = await locals.auth.validate();
// if (!session) {
// throw redirect(302, '/auth/signin');
// }
export const load: PageServerLoad = async ({ fetch, url, locals }) => {
const session = await locals.auth.validate();
if (!session) {
throw redirect(302, '/auth/signin');
}
console.log('locals load', locals);
// const searchParams = Object.fromEntries(url?.searchParams);
// const q = searchParams?.q;
// const limit = parseInt(searchParams?.limit) || 10;
// const skip = parseInt(searchParams?.skip) || 0;
// console.log('locals load', locals);
const searchParams = Object.fromEntries(url?.searchParams);
console.log('searchParams', searchParams);
const q = searchParams?.q;
const limit = parseInt(searchParams?.limit) || 10;
const skip = parseInt(searchParams?.skip) || 0;
// const searchData = {
// q,
// limit,
// skip
// };
const searchData = {
q,
limit,
skip
};
// const form = await superValidate(searchData, search_schema);
const searchForm = await superValidate(searchData, search_schema);
const listManageForm = await superValidate(modifyListGameSchema);
try {
// let collection = await locals.prisma.collection.findUnique({
// where: {
// user_id: session.userId
// }
// include: {
// collectionItems: {
// where: {
// title: {
// contains: q,
// mode: 'insensitive'
// }
// },
// take: limit,
// skip
// }
// }
// });
let collection = await prisma.collection.findUnique({
where: {
user_id: session.userId
}
});
console.log('collection', collection);
// console.log('collection', collection);
// if (!collection) {
// collection = await locals.prisma.collection.create({
// data: {
// user_id: session.userId
// }
// });
// }
if (!collection) {
console.log('Collection was not found');
return fail(404, {});
// collection = await prisma.collection.create({
// data: {
// user_id: session.userId
// }
// });
}
let collection_items: CollectionItemWithGame[] = await prisma.collectionItem.findMany({
where: {
collection_id: collection.id
},
include: {
game: {
select: {
id: true,
name: true,
thumb_url: true
}
}
},
skip,
take: limit
});
console.log('collection_items', collection_items);
let collectionItems: ListGame[] = [];
for (const item of collection_items) {
console.log('item', item);
const game = item.game;
if (game) {
let collectionItem: ListGame = {
id: item.id,
collection_id: item.collection_id,
game_id: game.id,
game_name: game.name,
thumb_url: game.thumb_url,
times_played: item.times_played,
wishlist_id: '',
in_collection: true
};
collectionItems.push(collectionItem);
}
}
return {
// form,
// collection
searchForm,
listManageForm,
collection: collectionItems
};
} catch (e) {
console.error(e);
}
return {
// form,
// collection: []
searchForm,
listManageForm,
collection: []
};
};
export const actions = {
// Add game to a wishlist
add: async (event) => {
const { params, locals, request } = event;
const form = await superValidate(event, modifyListGameSchema);
const session = await locals.auth.validate();
if (!session) {
throw redirect(302, '/auth/signin');
}
let game = await prisma.game.findUnique({
where: {
id: form.id
}
});
if (!game) {
game = await prisma.game.create({
data: {
name: form.name
}
});
throw redirect(302, '/404');
}
if (game) {
const wishlist = await prisma.wishlist.create({
data: {
user_id: session.userId,
name: form.name
}
});
}
return {
form
};
},
// Create new wishlist
create: async ({ params, locals, request }) => {
const session = await locals.auth.validate();
if (!session) {
throw redirect(302, '/auth/signin');
}
},
// Delete a wishlist
delete: async ({ params, locals, request }) => {
const session = await locals.auth.validate();
if (!session) {
throw redirect(302, '/auth/signin');
}
},
// Remove game from a wishlist
remove: async (event) => {
const { params, locals, request } = event;
const form = await superValidate(event, modifyListGameSchema);
const session = await locals.auth.validate();
if (!session) {
throw redirect(302, '/auth/signin');
}
console.log('form', form);
let collectionItem = await prisma.collectionItem.findUnique({
where: {
id: form.data.id
},
include: {
collection: {
select: {
user_id: true
}
}
}
});
console.log('collectionItem', collectionItem);
const belongsToUser = collectionItem?.collection?.user_id === session.userId;
console.log('belongsToUser', belongsToUser);
if (!collectionItem || !belongsToUser) {
// game = await prisma.game.create({
// data: {
// name: form.name
// }
// });
throw redirect(302, '/404');
}
if (collectionItem) {
console.log('Going to delete');
await prisma.collectionItem.delete({
where: {
id: collectionItem.id
}
});
}
return {
form,
collection: []
};
}
};

View file

@ -1,6 +1,10 @@
<script lang="ts">
// import { tick, onDestroy } from 'svelte';
// import Game from '$lib/components/game/index.svelte';
import Game from '$lib/components/game/index.svelte';
import type { SearchSchema } from '$lib/zodValidation.js';
import { superForm } from 'sveltekit-superforms/client';
import type { SuperValidated } from 'sveltekit-superforms';
import type { ModifyListGame } from '$lib/config/zod-schemas.js';
// import { collectionStore } from '$lib/stores/collectionStore';
// import type { GameType, SavedGameType } from '$lib/types';
// import { boredState } from '$lib/stores/boredState';
@ -11,7 +15,8 @@
export let data;
console.log(`Page data: ${JSON.stringify(data)}`);
// let collectionItems = data?.collection?.collectionItems;
let collectionItems = data?.collection || [];
console.log('collectionItems', collectionItems);
// let gameToRemove: GameType | SavedGameType;
// let pageSize = 10;
@ -82,21 +87,17 @@
<h1>Your Collection</h1>
<!-- <input type="text" id="search" name="search" placeholder="Search Your Collection" bind:value={$searchStore.search} /> -->
<!-- <div class="games">
<div class="games">
<div class="games-list">
{#if $collectionStore.length === 0}
{#if collectionItems.length === 0}
<h2>No games in your collection</h2>
{:else}
{#each gamesShown as game (game.id)}
<Game
on:handleRemoveWishlist={handleRemoveWishlist}
on:handleRemoveCollection={handleRemoveCollection}
{game}
/>
{#each collectionItems as game (game.game_id)}
<Game {game} data={data.listManageForm} />
{/each}
{/if}
</div>
{#if $collectionStore.length !== 0}
<!-- {#if $collectionStore.length !== 0}
<Pagination
{pageSize}
{page}
@ -108,8 +109,8 @@
on:previousPageEvent={handlePreviousPageEvent}
on:perPageEvent={handlePerPageEvent}
/>
{/if}
</div> -->
{/if} -->
</div>
<style lang="postcss">
h1 {

View file

@ -6,10 +6,11 @@ import prisma from '$lib/prisma.js';
import type { GameType, SearchQuery } from '$lib/types';
import { mapAPIGameToBoredGame } from '$lib/util/gameMapper';
import { search_schema } from '$lib/zodValidation';
import { listGameSchema } from '$lib/config/zod-schemas.js';
async function searchForGames(urlQueryParams: SearchQuery) {
async function searchForGames(urlQueryParams: SearchQuery, locals) {
try {
let dbGames = await prisma.game.findMany({
let games = await prisma.game.findMany({
where: {
name: {
search: urlQueryParams?.name
@ -36,9 +37,10 @@ async function searchForGames(urlQueryParams: SearchQuery) {
name: 'asc'
}
});
console.log('dbGames', dbGames);
console.log('games from DB', games);
let totalCount = games?.length || 0;
if (!dbGames || dbGames.length === 0) {
if (!games || games.length === 0) {
const url = new URL(
`https://api.boardgameatlas.com/api/search${urlQueryParams ? `?${urlQueryParams}` : ''}`
);
@ -55,8 +57,8 @@ async function searchForGames(urlQueryParams: SearchQuery) {
throw error(response.status);
}
const games: GameType[] = [];
let totalCount = 0;
// const games: GameType[] = [];
// let totalCount = 0;
if (response.ok) {
const gameResponse = await response.json();
const gameList: GameType[] = gameResponse?.games;
@ -72,16 +74,57 @@ async function searchForGames(urlQueryParams: SearchQuery) {
games.push(boredGame);
});
}
return {
totalCount,
games
};
} else {
return {
totalCount: dbGames.length,
games: dbGames
};
}
if (locals?.user) {
const game_ids = games.map((game) => game.id);
console.log('game_ids', game_ids);
const collections = await prisma.collection.findMany({
where: {
user_id: locals.user.id
},
include: {
items: {
where: {
game_id: {
in: game_ids
}
}
}
}
});
console.log('collections', collections);
const wishlists = await prisma.wishlist.findMany({
where: {
user_id: locals.user.id
},
include: {
items: {
where: {
id: {
in: game_ids
}
}
}
}
});
// console.log('wishlist_items', wishlist_items);
for (const game of games) {
console.log(
'Checking collection',
collections.findIndex((item) => item.items.some((i) => i.game_id === game.id))
);
game.in_collection =
collections.findIndex((item) => item.items.some((i) => i.game_id === game.id)) === 0;
game.in_wishlist =
wishlists.findIndex((item) => item.items.some((i) => i.game_id === game.id)) === 0;
}
}
return {
totalCount,
games
};
} catch (e) {
console.log(`Error searching board games ${e}`);
}
@ -178,9 +221,12 @@ export const load = async (event) => {
skip: 0
};
const searchParams = Object.fromEntries(url?.searchParams);
console.log('searchParams', searchParams);
searchParams.limit = searchParams.limit || `${defaults.limit}`;
searchParams.skip = searchParams.skip || `${defaults.skip}`;
searchParams.order = searchParams.order || 'asc';
const form = await superValidate(searchParams, search_schema);
const modifyListForm = await superValidate(listGameSchema);
const queryParams: SearchQuery = {
order_by: 'rank',
@ -223,10 +269,12 @@ export const load = async (event) => {
}
const urlQueryParams = new URLSearchParams(newQueryParams);
const searchData = await searchForGames(urlQueryParams, locals);
return {
form,
searchData: await searchForGames(urlQueryParams)
modifyListForm,
searchData
};
};

View file

@ -4,13 +4,14 @@
import TextSearch from '$lib/components/search/textSearch/index.svelte';
export let data;
console.log("search page data", data);
$: if (data?.searchData?.games) {
gameStore.removeAll();
gameStore.addAll(data?.searchData?.games);
}
// $: if (data?.searchData?.games) {
// gameStore.removeAll();
// gameStore.addAll(data?.searchData?.games);
// }
</script>
<div class="game-search">
<TextSearch showButton advancedSearch data={data.form} />
<TextSearch showButton advancedSearch {data} />
</div>