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" "seed": "ts-node --esm prisma/seed.ts"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.35.1", "@playwright/test": "^1.36.1",
"@sveltejs/adapter-auto": "^1.0.3", "@sveltejs/adapter-auto": "^1.0.3",
"@sveltejs/adapter-vercel": "^1.0.6", "@sveltejs/adapter-vercel": "^1.0.6",
"@sveltejs/kit": "^1.21.0", "@sveltejs/kit": "^1.22.3",
"@types/cookie": "^0.5.1", "@types/cookie": "^0.5.1",
"@types/node": "^18.16.19", "@types/node": "^18.16.19",
"@typescript-eslint/eslint-plugin": "^5.60.1", "@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.60.1", "@typescript-eslint/parser": "^5.62.0",
"autoprefixer": "^10.4.14", "autoprefixer": "^10.4.14",
"eslint": "^8.44.0", "eslint": "^8.45.0",
"eslint-config-prettier": "^8.8.0", "eslint-config-prettier": "^8.8.0",
"eslint-plugin-svelte": "^2.32.2", "eslint-plugin-svelte": "^2.32.2",
"just-clone": "^6.2.0", "just-clone": "^6.2.0",
"just-debounce-it": "^3.2.0", "just-debounce-it": "^3.2.0",
"postcss": "^8.4.24", "postcss": "^8.4.26",
"postcss-import": "^15.1.0", "postcss-import": "^15.1.0",
"postcss-load-config": "^4.0.1", "postcss-load-config": "^4.0.1",
"postcss-preset-env": "^8.5.1", "postcss-preset-env": "^8.5.1",
@ -47,12 +47,12 @@
"svelte": "^3.59.2", "svelte": "^3.59.2",
"svelte-check": "^2.10.3", "svelte-check": "^2.10.3",
"svelte-preprocess": "^5.0.4", "svelte-preprocess": "^5.0.4",
"sveltekit-superforms": "^1.1.3", "sveltekit-superforms": "^1.3.0",
"tailwindcss": "^3.3.2", "tailwindcss": "^3.3.3",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"tslib": "^2.6.0", "tslib": "^2.6.0",
"typescript": "^4.9.5", "typescript": "^4.9.5",
"vite": "^4.3.9", "vite": "^4.4.4",
"vitest": "^0.25.3", "vitest": "^0.25.3",
"zod": "^3.21.4" "zod": "^3.21.4"
}, },
@ -65,7 +65,7 @@
"@axiomhq/axiom-node": "^0.12.0", "@axiomhq/axiom-node": "^0.12.0",
"@fontsource/fira-mono": "^4.5.10", "@fontsource/fira-mono": "^4.5.10",
"@iconify-icons/line-md": "^1.2.23", "@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-side-menu": "^1.0.5",
"@leveluptuts/svelte-toy": "^2.0.3", "@leveluptuts/svelte-toy": "^2.0.3",
"@lucia-auth/adapter-mysql": "^1.1.1", "@lucia-auth/adapter-mysql": "^1.1.1",
@ -88,8 +88,8 @@
"svelte-lazy-loader": "^1.0.0", "svelte-lazy-loader": "^1.0.0",
"svelte-legos": "^0.2.1", "svelte-legos": "^0.2.1",
"sveltekit-flash-message": "^0.11.3", "sveltekit-flash-message": "^0.11.3",
"tailwind-merge": "^1.13.2", "tailwind-merge": "^1.14.0",
"tailwindcss-animate": "^1.0.6", "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 { model CollectionItem {
id String @id @default(cuid()) id String @id @default(cuid())
collection_id String collection_id String @unique
collection Collection @relation(references: [id], fields: [collection_id], onDelete: Cascade) 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]) game Game @relation(references: [id], fields: [game_id])
times_played Int times_played Int
@ -104,7 +104,7 @@ model CollectionItem {
model Wishlist { model Wishlist {
id String @id @default(cuid()) id String @id @default(cuid())
name String name String
user_id String user_id String @unique
auth_user AuthUser @relation(references: [id], fields: [user_id]) auth_user AuthUser @relation(references: [id], fields: [user_id])
items WishlistItem[] items WishlistItem[]
@ -114,9 +114,9 @@ model Wishlist {
model WishlistItem { model WishlistItem {
id String @id @default(cuid()) id String @id @default(cuid())
wishlist_id String wishlist_id String @unique
wishlist Wishlist @relation(references: [id], fields: [wishlist_id], onDelete: Cascade) 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]) game Game @relation(references: [id], fields: [game_id])
created_at DateTime @default(now()) @db.Timestamp(6) created_at DateTime @default(now()) @db.Timestamp(6)
updated_at DateTime @updatedAt @db.Timestamp(6) updated_at DateTime @updatedAt @db.Timestamp(6)

2
src/app.d.ts vendored
View file

@ -4,7 +4,7 @@
import type { AuthUser } from '@prisma/client'; 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 // src/app.d.ts
declare global { declare global {

View file

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

View file

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

View file

@ -18,22 +18,20 @@
// import SkeletonPlaceholder from '../../SkeletonPlaceholder.svelte'; // import SkeletonPlaceholder from '../../SkeletonPlaceholder.svelte';
import RemoveCollectionDialog from '../../dialog/RemoveCollectionDialog.svelte'; import RemoveCollectionDialog from '../../dialog/RemoveCollectionDialog.svelte';
import RemoveWishlistDialog from '../../dialog/RemoveWishlistDialog.svelte'; import RemoveWishlistDialog from '../../dialog/RemoveWishlistDialog.svelte';
import type { SearchSchema } from '$lib/zodValidation'; import type { ListGameSchema, SearchSchema } from '$lib/zodValidation';
interface RemoveGameEvent extends Event { interface RemoveGameEvent extends Event {
detail: GameType | SavedGameType; detail: GameType | SavedGameType;
} }
export let data: SuperValidated<SearchSchema>; export let data;
const { form, constraints, errors } = superForm(data, { console.log("text search data", data);
onSubmit: () => {
boredState.update((n) => ({ ...n, loading: true }));
},
});
export let showButton: boolean = false; export let showButton: boolean = false;
export let advancedSearch: 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 gameToRemove: GameType | SavedGameType;
let numberOfGameSkeleton = 1; let numberOfGameSkeleton = 1;
let submitButton: HTMLElement; let submitButton: HTMLElement;
@ -58,11 +56,11 @@
numberOfGameSkeleton = 1; numberOfGameSkeleton = 1;
} }
let placeholderList = [...Array(numberOfGameSkeleton).keys()]; // let placeholderList = [...Array(numberOfGameSkeleton).keys()];
if (form?.error) { // if (form?.error) {
disclosureOpen = true; // disclosureOpen = true;
} // }
async function handleNextPageEvent(event: CustomEvent) { async function handleNextPageEvent(event: CustomEvent) {
if (+event?.detail?.page === page + 1) { if (+event?.detail?.page === page + 1) {
@ -87,53 +85,53 @@
submitButton.click(); submitButton.click();
} }
function handleRemoveCollection(event: RemoveGameEvent) { // function handleRemoveCollection(event: RemoveGameEvent) {
gameToRemove = event?.detail; // gameToRemove = event?.detail;
boredState.update((n) => ({ // boredState.update((n) => ({
...n, // ...n,
dialog: { isOpen: true, content: RemoveCollectionDialog, additionalData: gameToRemove } // dialog: { isOpen: true, content: RemoveCollectionDialog, additionalData: gameToRemove }
})); // }));
} // }
function handleRemoveWishlist(event: RemoveGameEvent) { // function handleRemoveWishlist(event: RemoveGameEvent) {
gameToRemove = event?.detail; // gameToRemove = event?.detail;
boredState.update((n) => ({ // boredState.update((n) => ({
...n, // ...n,
dialog: { isOpen: true, content: RemoveWishlistDialog, additionalData: gameToRemove } // dialog: { isOpen: true, content: RemoveWishlistDialog, additionalData: gameToRemove }
})); // }));
} // }
const submitSearch: SubmitFunction = ({ form, data, action, cancel }) => { // const submitSearch: SubmitFunction = ({ form, data, action, cancel }) => {
const { name } = Object.fromEntries(data); // const { name } = Object.fromEntries(data);
if (!disclosureOpen && name?.length === 0) { // if (!disclosureOpen && name?.length === 0) {
toast.send('Please enter a search term', { // toast.send('Please enter a search term', {
duration: 3000, // duration: 3000,
type: ToastType.ERROR, // type: ToastType.ERROR,
dismissible: true // dismissible: true
}); // });
cancel(); // cancel();
return; // return;
} // }
gameStore.removeAll(); // gameStore.removeAll();
boredState.update((n) => ({ ...n, loading: true })); // boredState.update((n) => ({ ...n, loading: true }));
return async ({ result }) => { // return async ({ result }) => {
boredState.update((n) => ({ ...n, loading: false })); // boredState.update((n) => ({ ...n, loading: false }));
// `result` is an `ActionResult` object // // `result` is an `ActionResult` object
if (result.type === 'error') { // if (result.type === 'error') {
toast.send('Error!', { duration: 3000, type: ToastType.ERROR, dismissible: true }); // toast.send('Error!', { duration: 3000, type: ToastType.ERROR, dismissible: true });
await applyAction(result); // await applyAction(result);
} else if (result.type === 'success') { // } else if (result.type === 'success') {
gameStore.removeAll(); // gameStore.removeAll();
gameStore.addAll(result?.data?.searchData?.games); // gameStore.addAll(result?.data?.searchData?.games);
totalItems = result?.data?.searchData?.totalCount; // totalItems = result?.data?.searchData?.totalCount;
// toast.send('Success!', { duration: 3000, type: ToastType.INFO, dismissible: true }); // // toast.send('Success!', { duration: 3000, type: ToastType.INFO, dismissible: true });
await applyAction(result); // await applyAction(result);
} else { // } else {
await applyAction(result); // await applyAction(result);
} // }
}; // };
}; // };
const dev = process.env.NODE_ENV !== 'production'; const dev = process.env.NODE_ENV !== 'production';
@ -226,11 +224,7 @@
<div class="games-list"> <div class="games-list">
{#if $gameStore?.length > 0} {#if $gameStore?.length > 0}
{#each $gameStore as game (game.id)} {#each $gameStore as game (game.id)}
<Game <Game {game} data={modifyListForm} />
on:handleRemoveWishlist={handleRemoveWishlist}
on:handleRemoveCollection={handleRemoveCollection}
{game}
/>
{/each} {/each}
{:else} {:else}
<h2>Sorry no games found!</h2> <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'; 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({ export const userSchema = z.object({
firstName: z.string().trim().optional(), firstName: z.string().trim().optional(),
lastName: 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'; 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 = { export type Dialog = {
isOpen: boolean; isOpen: boolean;
content?: typeof SvelteComponent; content?: typeof SvelteComponent;
@ -57,6 +72,15 @@ export type SavedGameType = {
includeInRandom: boolean; 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 = { export type MechanicType = {
id: string; 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 export const search_schema = z
.object({ .object({
q: z.string().trim().optional().default(''), q: z.string().trim().optional().default(''),
@ -45,6 +59,8 @@ export const search_schema = z
exactMinAge: z.preprocess((a) => Boolean(a), z.boolean().optional()), exactMinAge: z.preprocess((a) => Boolean(a), z.boolean().optional()),
exactMinPlayers: 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()), 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), limit: z.number().min(10).max(100).default(10),
skip: z.number().min(0).default(0) skip: z.number().min(0).default(0)
}) })
@ -92,6 +108,12 @@ export const search_schema = z
export type SearchSchema = typeof search_schema; 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({ export const search_result_schema = z.object({
client_id: z.string(), client_id: z.string(),
limit: z.number(), 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) { } catch (e) {
// TODO: need to return error message to the client // TODO: need to return error message to the client
console.error(e); console.error(e);

View file

@ -3,6 +3,7 @@ import { setError, superValidate } from 'sveltekit-superforms/server';
import { auth } from '$lib/server/lucia'; import { auth } from '$lib/server/lucia';
import { userSchema } from '$lib/config/zod-schemas'; import { userSchema } from '$lib/config/zod-schemas';
import { add_user_to_role } from '$db/roles'; import { add_user_to_role } from '$db/roles';
import prisma from '$lib/prisma.js';
const signUpSchema = userSchema const signUpSchema = userSchema
.pick({ .pick({
@ -73,6 +74,17 @@ export const actions = {
} }
}); });
add_user_to_role(user.id, 'user'); 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); console.log('User', user);

View file

@ -32,9 +32,7 @@ import { userSchema } from '$lib/config/zod-schemas.js';
Signup for an account Signup for an account
</h2> </h2>
<Label for="firstName">First Name</Label> <Label for="firstName">First Name</Label>
<Input <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} />
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} {#if $errors.firstName}
<p class="text-sm text-destructive">{$errors.firstName}</p> <p class="text-sm text-destructive">{$errors.firstName}</p>
{/if} {/if}

View file

@ -1,65 +1,207 @@
// import { redirect } from '@sveltejs/kit'; import { fail, redirect } from '@sveltejs/kit';
// import { superValidate } from 'sveltekit-superforms/server'; import { setError, superValidate } from 'sveltekit-superforms/server';
// import { search_schema } from '$lib/zodValidation'; 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 }) => { export const load: PageServerLoad = async ({ fetch, url, locals }) => {
// const session = await locals.auth.validate(); const session = await locals.auth.validate();
// if (!session) { if (!session) {
// throw redirect(302, '/auth/signin'); throw redirect(302, '/auth/signin');
// } }
console.log('locals load', locals); // console.log('locals load', locals);
// const searchParams = Object.fromEntries(url?.searchParams); const searchParams = Object.fromEntries(url?.searchParams);
// const q = searchParams?.q; console.log('searchParams', searchParams);
// const limit = parseInt(searchParams?.limit) || 10; const q = searchParams?.q;
// const skip = parseInt(searchParams?.skip) || 0; const limit = parseInt(searchParams?.limit) || 10;
const skip = parseInt(searchParams?.skip) || 0;
// const searchData = { const searchData = {
// q, q,
// limit, limit,
// skip skip
// }; };
// const form = await superValidate(searchData, search_schema); const searchForm = await superValidate(searchData, search_schema);
const listManageForm = await superValidate(modifyListGameSchema);
try { try {
// let collection = await locals.prisma.collection.findUnique({ let collection = await prisma.collection.findUnique({
// where: { where: {
// user_id: session.userId user_id: session.userId
// } }
// include: { });
// collectionItems: { console.log('collection', collection);
// where: {
// title: {
// contains: q,
// mode: 'insensitive'
// }
// },
// take: limit,
// skip
// }
// }
// });
// console.log('collection', collection); if (!collection) {
// if (!collection) { console.log('Collection was not found');
// collection = await locals.prisma.collection.create({ return fail(404, {});
// data: { // collection = await prisma.collection.create({
// user_id: session.userId // 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 { return {
// form, searchForm,
// collection listManageForm,
collection: collectionItems
}; };
} catch (e) { } catch (e) {
console.error(e); console.error(e);
} }
return { return {
// form, searchForm,
// collection: [] 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"> <script lang="ts">
// import { tick, onDestroy } from 'svelte'; // 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 { collectionStore } from '$lib/stores/collectionStore';
// import type { GameType, SavedGameType } from '$lib/types'; // import type { GameType, SavedGameType } from '$lib/types';
// import { boredState } from '$lib/stores/boredState'; // import { boredState } from '$lib/stores/boredState';
@ -11,7 +15,8 @@
export let data; export let data;
console.log(`Page data: ${JSON.stringify(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 gameToRemove: GameType | SavedGameType;
// let pageSize = 10; // let pageSize = 10;
@ -82,21 +87,17 @@
<h1>Your Collection</h1> <h1>Your Collection</h1>
<!-- <input type="text" id="search" name="search" placeholder="Search Your Collection" bind:value={$searchStore.search} /> --> <!-- <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"> <div class="games-list">
{#if $collectionStore.length === 0} {#if collectionItems.length === 0}
<h2>No games in your collection</h2> <h2>No games in your collection</h2>
{:else} {:else}
{#each gamesShown as game (game.id)} {#each collectionItems as game (game.game_id)}
<Game <Game {game} data={data.listManageForm} />
on:handleRemoveWishlist={handleRemoveWishlist}
on:handleRemoveCollection={handleRemoveCollection}
{game}
/>
{/each} {/each}
{/if} {/if}
</div> </div>
{#if $collectionStore.length !== 0} <!-- {#if $collectionStore.length !== 0}
<Pagination <Pagination
{pageSize} {pageSize}
{page} {page}
@ -108,8 +109,8 @@
on:previousPageEvent={handlePreviousPageEvent} on:previousPageEvent={handlePreviousPageEvent}
on:perPageEvent={handlePerPageEvent} on:perPageEvent={handlePerPageEvent}
/> />
{/if} {/if} -->
</div> --> </div>
<style lang="postcss"> <style lang="postcss">
h1 { h1 {

View file

@ -6,10 +6,11 @@ import prisma from '$lib/prisma.js';
import type { GameType, SearchQuery } from '$lib/types'; import type { GameType, SearchQuery } from '$lib/types';
import { mapAPIGameToBoredGame } from '$lib/util/gameMapper'; import { mapAPIGameToBoredGame } from '$lib/util/gameMapper';
import { search_schema } from '$lib/zodValidation'; 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 { try {
let dbGames = await prisma.game.findMany({ let games = await prisma.game.findMany({
where: { where: {
name: { name: {
search: urlQueryParams?.name search: urlQueryParams?.name
@ -36,9 +37,10 @@ async function searchForGames(urlQueryParams: SearchQuery) {
name: 'asc' 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( const url = new URL(
`https://api.boardgameatlas.com/api/search${urlQueryParams ? `?${urlQueryParams}` : ''}` `https://api.boardgameatlas.com/api/search${urlQueryParams ? `?${urlQueryParams}` : ''}`
); );
@ -55,8 +57,8 @@ async function searchForGames(urlQueryParams: SearchQuery) {
throw error(response.status); throw error(response.status);
} }
const games: GameType[] = []; // const games: GameType[] = [];
let totalCount = 0; // let totalCount = 0;
if (response.ok) { if (response.ok) {
const gameResponse = await response.json(); const gameResponse = await response.json();
const gameList: GameType[] = gameResponse?.games; const gameList: GameType[] = gameResponse?.games;
@ -72,16 +74,57 @@ async function searchForGames(urlQueryParams: SearchQuery) {
games.push(boredGame); 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) { } catch (e) {
console.log(`Error searching board games ${e}`); console.log(`Error searching board games ${e}`);
} }
@ -178,9 +221,12 @@ export const load = async (event) => {
skip: 0 skip: 0
}; };
const searchParams = Object.fromEntries(url?.searchParams); const searchParams = Object.fromEntries(url?.searchParams);
console.log('searchParams', searchParams);
searchParams.limit = searchParams.limit || `${defaults.limit}`; searchParams.limit = searchParams.limit || `${defaults.limit}`;
searchParams.skip = searchParams.skip || `${defaults.skip}`; searchParams.skip = searchParams.skip || `${defaults.skip}`;
searchParams.order = searchParams.order || 'asc';
const form = await superValidate(searchParams, search_schema); const form = await superValidate(searchParams, search_schema);
const modifyListForm = await superValidate(listGameSchema);
const queryParams: SearchQuery = { const queryParams: SearchQuery = {
order_by: 'rank', order_by: 'rank',
@ -223,10 +269,12 @@ export const load = async (event) => {
} }
const urlQueryParams = new URLSearchParams(newQueryParams); const urlQueryParams = new URLSearchParams(newQueryParams);
const searchData = await searchForGames(urlQueryParams, locals);
return { return {
form, form,
searchData: await searchForGames(urlQueryParams) modifyListForm,
searchData
}; };
}; };

View file

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