Update Lucia to V2, add APIs for user interactions, and fix anything to get the build working.

This commit is contained in:
Bradley Shellnut 2023-07-29 22:00:51 -07:00
parent 4905ee152c
commit 1f1d9d7838
20 changed files with 814 additions and 630 deletions

View file

@ -22,37 +22,38 @@
"seed": "ts-node --esm prisma/seed.ts"
},
"devDependencies": {
"@playwright/test": "^1.36.1",
"@playwright/test": "^1.36.2",
"@sveltejs/adapter-auto": "^1.0.3",
"@sveltejs/adapter-vercel": "^1.0.6",
"@sveltejs/kit": "^1.22.3",
"@types/cookie": "^0.5.1",
"@types/node": "^18.16.19",
"@types/node": "^18.17.1",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"autoprefixer": "^10.4.14",
"eslint": "^8.45.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-svelte": "^2.32.2",
"eslint-plugin-svelte": "^2.32.4",
"just-clone": "^6.2.0",
"just-debounce-it": "^3.2.0",
"postcss": "^8.4.26",
"postcss": "^8.4.27",
"postcss-import": "^15.1.0",
"postcss-load-config": "^4.0.1",
"postcss-preset-env": "^8.5.1",
"prettier": "^2.8.8",
"prettier-plugin-svelte": "^2.10.1",
"prisma": "^4.16.2",
"sass": "^1.63.6",
"svelte": "^4.0.0",
"svelte-check": "^3.4.3",
"sass": "^1.64.1",
"svelte": "^4.1.1",
"svelte-check": "^3.4.6",
"svelte-preprocess": "^5.0.4",
"sveltekit-superforms": "^1.3.0",
"sveltekit-flash-message": "^2.1.0",
"sveltekit-superforms": "^1.5.0",
"tailwindcss": "^3.3.3",
"ts-node": "^10.9.1",
"tslib": "^2.6.0",
"typescript": "^5.0.0",
"vite": "^4.4.4",
"tslib": "^2.6.1",
"typescript": "^5.1.6",
"vite": "^4.4.7",
"vitest": "^0.25.3",
"zod": "^3.21.4"
},
@ -69,9 +70,9 @@
"@leveluptuts/svelte-side-menu": "^1.0.5",
"@leveluptuts/svelte-toy": "^2.0.3",
"@lucia-auth/adapter-mysql": "^1.1.1",
"@lucia-auth/adapter-prisma": "^2.0.0",
"@lucia-auth/adapter-prisma": "^3.0.0",
"@lukeed/uuid": "^2.0.1",
"@prisma/client": "4.16.1",
"@prisma/client": "4.16.2",
"@types/feather-icons": "^4.29.1",
"class-variance-authority": "^0.6.1",
"clsx": "^1.2.1",
@ -80,16 +81,15 @@
"iconify-icon": "^1.0.8",
"just-kebab-case": "^4.2.0",
"loader": "^2.1.1",
"lucia-auth": "^1.8.0",
"lucia": "^2.0.0",
"lucide-svelte": "^0.256.1",
"open-props": "^1.5.10",
"radix-svelte": "^0.8.0",
"svelte-lazy": "^1.2.1",
"svelte-lazy-loader": "^1.0.0",
"svelte-legos": "^0.2.1",
"sveltekit-flash-message": "^0.11.3",
"tailwind-merge": "^1.14.0",
"tailwindcss-animate": "^1.0.6",
"zod-to-json-schema": "^3.21.4"
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -22,10 +22,10 @@ model Role {
model UserRole {
id String @id @default(cuid())
user AuthUser @relation(fields: [user_id], references: [id])
user_id String
user User @relation(fields: [user_id], references: [id])
user_id String
role Role @relation(fields: [role_id], references: [id])
role_id String
role_id String
created_at DateTime @default(now()) @db.Timestamp(6)
updated_at DateTime @updatedAt @db.Timestamp(6)
@ -35,7 +35,7 @@ model UserRole {
@@map("user_roles")
}
model AuthUser {
model User {
id String @id @default(cuid())
username String @unique
email String? @unique
@ -50,39 +50,37 @@ model AuthUser {
theme String @default("system")
created_at DateTime @default(now()) @db.Timestamp(6)
updated_at DateTime @updatedAt @db.Timestamp(6)
auth_session AuthSession[]
auth_key AuthKey[]
auth_session Session[]
auth_key Key[]
@@map("auth_user")
@@map("users")
}
model AuthSession {
model Session {
id String @id @unique
user_id String
active_expires BigInt
idle_expires BigInt
auth_user AuthUser @relation(references: [id], fields: [user_id], onDelete: Cascade)
user User @relation(references: [id], fields: [user_id], onDelete: Cascade)
@@index([user_id])
@@map("auth_session")
@@map("sessions")
}
model AuthKey {
model Key {
id String @id @unique
hashed_password String?
user_id String
primary_key Boolean
expires BigInt?
auth_user AuthUser @relation(references: [id], fields: [user_id], onDelete: Cascade)
user User @relation(references: [id], fields: [user_id], onDelete: Cascade)
@@index([user_id])
@@map("auth_key")
@@map("keys")
}
model Collection {
id String @id @default(cuid())
user_id String @unique
auth_user AuthUser @relation(references: [id], fields: [user_id])
user User @relation(references: [id], fields: [user_id])
items CollectionItem[]
@@index([user_id])
@ -105,7 +103,7 @@ model Wishlist {
id String @id @default(cuid())
name String
user_id String @unique
auth_user AuthUser @relation(references: [id], fields: [user_id])
user User @relation(references: [id], fields: [user_id])
items WishlistItem[]
@@index([user_id])

13
src/app.d.ts vendored
View file

@ -2,9 +2,9 @@
// for information about these interfaces
// and what to do when importing types
import type { AuthUser } from '@prisma/client';
import type { User } from '@prisma/client';
type User = Omit<AuthUser, 'created_at' | 'updated_at'>;
type User = Omit<User, 'created_at' | 'updated_at'>;
// src/app.d.ts
declare global {
@ -13,7 +13,7 @@ declare global {
flash?: { type: 'success' | 'error'; message: string };
}
interface Locals {
auth: import('lucia-auth').AuthRequest;
auth: import('lucia').AuthRequest;
prisma: PrismaClient;
user: Lucia.UserAttributes;
startTimer: number;
@ -34,11 +34,12 @@ declare global {
// interface Error {}
// interface Platform {}
/// <reference types="lucia-auth" />
/// <reference types="lucia" />
declare global {
namespace Lucia {
type Auth = import('$lib/lucia').Auth;
type UserAttributes = User;
type Auth = import('$lib/server/lucia').Auth;
type DatabaseUserAttributes = User;
type DatabaseSessionAttributes = {};
}
}

View file

@ -1,18 +1,18 @@
import { auth } from '$lib/server/lucia';
import prisma from '$lib/prisma';
import type { AuthUser } from '@prisma/client';
import type { User } from '@prisma/client';
import { add_user_to_role } from './roles';
export function create_user(user: AuthUser) {
return prisma.authUser.create({
export function create_user(user: User) {
return prisma.user.create({
data: {
username: user.username
}
});
}
export async function find_or_create_user(user: AuthUser) {
const existing_user = await prisma.authUser.findUnique({
export async function find_or_create_user(user: User) {
const existing_user = await prisma.user.findUnique({
where: {
username: user.username
}
@ -27,7 +27,7 @@ export async function find_or_create_user(user: AuthUser) {
}
export async function find_user_with_roles(user_id: string) {
const user_with_roles = await prisma.authUser.findUnique({
const user_with_roles = await prisma.user.findUnique({
where: {
id: user_id
},

View file

@ -1,9 +1,8 @@
import { sequence } from '@sveltejs/kit/hooks';
import { redirect, type HandleServerError, type Handle } from '@sveltejs/kit';
import { type HandleServerError, type Handle } from '@sveltejs/kit';
import { dev } from '$app/environment';
import { auth } from '$lib/server/lucia';
import log from '$lib/server/log';
import prisma from '$lib/config/prisma';
export const handleError: HandleServerError = async ({ error, event }) => {
const errorId = crypto.randomUUID();
@ -36,13 +35,21 @@ export const authentication: Handle = async function ({ event, resolve }) {
event.locals.startTimer = startTimer;
event.locals.auth = auth.handleRequest(event);
if (event.locals?.auth) {
const { user } = await event.locals.auth.validateUser();
event.locals.user = user;
// if (event.route.id?.startsWith('/(protected)')) {
// if (!user) throw redirect(302, '/auth/sign-in');
// if (!user.verified) throw redirect(302, '/auth/verify/email');
// }
if (event?.locals?.auth) {
console.log('auth not empty');
try {
const session = await event.locals.auth.validate();
console.log('user', session?.user);
event.locals.user = session?.user;
// if (event.route.id?.startsWith('/(protected)')) {
// if (!user) throw redirect(302, '/auth/sign-in');
// if (!user.verified) throw redirect(302, '/auth/verify/email');
// }
} catch (error) {
console.error('Error validating user', error);
}
} else {
console.log('auth empty');
}
const response = await resolve(event);

View file

@ -20,21 +20,22 @@
import type { ListGameSchema } from '$lib/zodValidation';
import type { CollectionItem } from '@prisma/client';
export let data: SuperValidated<ListGameSchema>;
// export let data: SuperValidated<ListGameSchema>;
export let game: GameType | CollectionItem;
export let detailed: boolean = false;
const { form, errors, enhance, delayed } = superForm(data);
// const { form, errors, enhance, delayed } = superForm(data);
// data={modifyListForm}
const dispatch = createEventDispatcher();
// const dispatch = createEventDispatcher();
function removeGameFromWishlist() {
dispatch('handleRemoveWishlist', game);
}
// function removeGameFromWishlist() {
// dispatch('handleRemoveWishlist', game);
// }
function removeGameFromCollection() {
dispatch('handleRemoveCollection', game);
}
// function removeGameFromCollection() {
// dispatch('handleRemoveCollection', game);
// }
function onCollectionClick() {
if (existsInCollection) {
@ -88,16 +89,16 @@
<article class="grid grid-template-cols-2 gap-4" transition:fade|global>
<Card>
<CardHeader>
<CardTitle>{game.game_name}</CardTitle>
<CardTitle>{game.name}</CardTitle>
</CardHeader>
<CardContent>
<a
class="thumbnail"
href={`/game/${game.game_id}`}
href={`/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" />
<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>
@ -114,7 +115,7 @@
</CardContent>
<CardFooter>
<div class="grid gap-2 place-items-center">
<form method="POST" use:enhance action={`/collection?/${existsInCollection ? 'remove' : 'add'}`}>
<form method="POST" action={`/collection?/${existsInCollection ? 'remove' : 'add'}`}>
<input type="hidden" name="id" value={game.id} />
<Button variant={existsInCollection ? 'destructive' : 'default'} on:click={onCollectionClick}>
{collectionText}
@ -125,7 +126,7 @@
{/if}
</Button>
</form>
<form method="POST" use:enhance action={`/wishlist?/${existsInWishlist ? 'remove' : 'add'}`}>
<form method="POST" action={`/wishlist?/${existsInWishlist ? 'remove' : 'add'}`}>
<input type="hidden" name="id" value={game.id} />
<Button variant={existsInWishlist ? 'destructive' : 'default'} on:click={onWishlistClick}>
{wishlistText}

View file

@ -29,8 +29,9 @@
export let showButton: boolean = false;
export let advancedSearch: boolean = false;
const { games, totalCount } = data?.searchData;
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);
// const { form: modifyListForm, errors: listErrors, constraints: listConstraints, enhance: listEnhance, message: listMessage } : SuperValidated<ListGameSchema> = superForm(data.modifyListForm);
let gameToRemove: GameType | SavedGameType;
let numberOfGameSkeleton = 1;
@ -43,8 +44,8 @@
let name = form?.name || '';
let disclosureOpen = $errors.length > 0 || false;
$: skip = (page - 1) * pageSize;
$: showPagination = $gameStore?.length > 1;
// $: skip = (page - 1) * pageSize;
// $: showPagination = $gameStore?.length > 1;
if ($xl) {
numberOfGameSkeleton = 8;
@ -222,9 +223,9 @@
<div class="games">
<h1>Games Found:</h1>
<div class="games-list">
{#if $gameStore?.length > 0}
{#each $gameStore as game (game.id)}
<Game {game} data={modifyListForm} />
{#if totalCount > 0}
{#each games as game (game.id)}
<Game {game} />
{/each}
{:else}
<h2>Sorry no games found!</h2>

View file

@ -1,25 +1,26 @@
// lib/server/lucia.ts
import lucia from 'lucia-auth';
import { sveltekit } from 'lucia-auth/middleware';
import prisma from '@lucia-auth/adapter-prisma';
import { lucia } from 'lucia';
import { sveltekit } from 'lucia/middleware';
import { prisma } from '@lucia-auth/adapter-prisma';
import { PrismaClient } from '@prisma/client';
import { dev } from '$app/environment';
const client = new PrismaClient();
export const auth = lucia({
adapter: prisma(new PrismaClient()),
adapter: prisma(client),
env: dev ? 'DEV' : 'PROD',
middleware: sveltekit(),
transformDatabaseUser: (userData) => {
getUserAttributes: (databaseUser) => {
return {
id: userData.id,
username: userData.username,
email: userData.email,
firstName: userData.firstName,
lastName: userData.lastName,
verified: userData.verified,
receiveEmail: userData.receiveEmail,
token: userData.token,
theme: userData.theme
username: databaseUser.username,
email: databaseUser.email,
firstName: databaseUser.firstName,
lastName: databaseUser.lastName,
verified: databaseUser.verified,
receiveEmail: databaseUser.receiveEmail,
token: databaseUser.token,
theme: databaseUser.theme
};
},
experimental: {

View file

@ -60,7 +60,7 @@ export const search_schema = z
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(),
order: 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)
})

View file

@ -1,6 +1,11 @@
export const load = async ({ url, locals }) => {
import { loadFlash } from 'sveltekit-flash-message/server';
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ url, locals }) => {
return {
url: url.pathname,
user: locals.user
};
};
// loadFlash(

View file

@ -1,9 +1,11 @@
<script lang="ts">
import "../app.postcss";
import { onMount } from "svelte";
// import { getFlash } from 'sveltekit-flash-message/client';
import { navigating, page } from '$app/stores';
import { browser } from '$app/environment';
import { navigating } from '$app/stores';
import debounce from 'just-debounce-it';
import { Toy } from '@leveluptuts/svelte-toy';
// import { Toy } from '@leveluptuts/svelte-toy';
import 'iconify-icon';
import Analytics from '$lib/components/analytics.svelte';
import Header from '$lib/components/header/index.svelte';
@ -14,13 +16,10 @@
import { boredState } from '$lib/stores/boredState';
import { collectionStore } from '$lib/stores/collectionStore';
import { wishlistStore } from '$lib/stores/wishlistStore';
import { gameStore } from '$lib/stores/gameSearchStore';
import { toast } from '$lib/components/toast/toast';
import Toast from '$lib/components/toast/Toast.svelte';
import { theme } from '$state/theme';
// import '$styles/styles.pcss';
import type { SavedGameType } from '$lib/types';
import { onMount } from "svelte";
$: {
if ($navigating) {
@ -34,6 +33,7 @@
}
$: isOpen = $boredState?.dialog?.isOpen;
// const flash = getFlash(page);
if (browser) {
const collator = new Intl.Collator('en');
@ -121,6 +121,10 @@
</div>
{/if}
<Toast></Toast>
<!-- {#if $flash}
{@const bg = $flash.type == 'success' ? '#3D9970' : '#FF4136'}
<div style:background-color={bg} class="flash">{$flash.message}</div>
{/if} -->
<style lang="postcss">
.loading {

View file

@ -10,9 +10,9 @@ export const load = async ({ fetch, url }) => {
return { form };
};
export const actions = {
default: async ({ request, locals }): Promise<any> => {
// Do things in here
return {};
}
};
// export const actions = {
// default: async ({ request, locals }): Promise<any> => {
// // Do things in here
// return {};
// }
// };

View file

@ -24,7 +24,7 @@
<Random />
</div>
</section>
<TextSearch showButton advancedSearch data={data.form} />
<!-- <TextSearch showButton advancedSearch data={data.form} /> -->
</div>
<style lang="scss">

View file

@ -0,0 +1,29 @@
import { error } from '@sveltejs/kit';
// Fetch collection for user
export function GET({ url }) {
const searchParams = Object.fromEntries(url.searchParams);
const q = searchParams?.q;
const limit = parseInt(searchParams?.limit) || 10;
const skip = parseInt(searchParams?.skip) || 0;
return new Response();
}
// Create a new collection for user
export function POST({ url }) {
const searchParams = Object.fromEntries(url.searchParams);
const q = searchParams?.q;
const limit = parseInt(searchParams?.limit) || 10;
const skip = parseInt(searchParams?.skip) || 0;
}
// Update or Create a collection
export function PUT({ url }) {
const searchParams = Object.fromEntries(url.searchParams);
const q = searchParams?.q;
const limit = parseInt(searchParams?.limit) || 10;
const skip = parseInt(searchParams?.skip) || 0;
}
//

View file

@ -21,7 +21,7 @@ export async function GET({ url, locals, params }) {
let collection = await prisma.collection.findUnique({
where: {
user_id: locals.user.id
user_id: locals.user.userId
}
});
console.log('collection', collection);

View file

@ -10,6 +10,7 @@ const signInSchema = userSchema.pick({
});
export const load = async (event) => {
console.log('sign in load event', event);
const session = await event.locals.auth.validate();
if (session) {
throw redirect(302, '/');
@ -33,7 +34,10 @@ export const actions = {
try {
const key = await auth.useKey('username', form.data.username, form.data.password);
const session = await auth.createSession(key.userId);
const session = await auth.createSession({
userId: key.userId,
attributes: {}
});
event.locals.auth.setSession(session);
const user = await prisma.authUser.findUnique({

View file

@ -1,5 +1,7 @@
import { fail, redirect } from '@sveltejs/kit';
import { setError, superValidate } from 'sveltekit-superforms/server';
import { redirect as flashRedirect } from 'sveltekit-flash-message/server';
import { LuciaError } from 'lucia';
import { auth } from '$lib/server/lucia';
import { userSchema } from '$lib/config/zod-schemas';
import { add_user_to_role } from '$db/roles';
@ -31,6 +33,7 @@ const signUpSchema = userSchema
});
export const load = async (event) => {
console.log('sign up load event', event);
const session = await event.locals.auth.validate();
if (session) {
throw redirect(302, '/');
@ -57,7 +60,7 @@ export const actions = {
const token = crypto.randomUUID();
const user = await auth.createUser({
primaryKey: {
key: {
providerId: 'username',
providerUserId: form.data.username,
password: form.data.password
@ -73,28 +76,36 @@ export const actions = {
token
}
});
add_user_to_role(user.id, 'user');
console.log('signup user', user);
add_user_to_role(user.userId, 'user');
await prisma.collection.create({
data: {
user_id: user.id
user_id: user.userId
}
});
await prisma.wishlist.create({
data: {
user_id: user.id,
user_id: user.userId,
name: 'My Wishlist'
}
});
console.log('User', user);
const session = await auth.createSession(user.id);
const session = await auth.createSession({
userId: user.userId,
attributes: {}
});
event.locals.auth.setSession(session);
// const message = { type: 'success', message: 'Signed Up!' } as const;
// throw flashRedirect(message, event);
} catch (error) {
if (error instanceof LuciaError && error.message === `DUPLICATE_KEY_ID`) {
// key already exists
console.error(error);
}
console.log(error);
return setError(form, '', 'Unable to create your account. Please try again.');
}
return { form };
}
};

View file

@ -3,18 +3,9 @@
import { Image } from 'svelte-lazy-loader';
import minusCircle from '@iconify-icons/line-md/minus-circle';
import plusCircle from '@iconify-icons/line-md/plus-circle';
// import {
// ChevronRightIcon,
// ExternalLinkIcon,
// MinusCircleIcon,
// MinusIcon,
// PlusCircleIcon,
// PlusIcon
// } from '@rgossiaux/svelte-heroicons/outline';
import type { GameType, SavedGameType } from '$lib/types';
import { collectionStore } from '$lib/stores/collectionStore';
import { wishlistStore } from '$lib/stores/wishlistStore';
import Button from '$lib/components/button/index.svelte';
import RemoveCollectionDialog from '$lib/components/dialog/RemoveCollectionDialog.svelte';
import { addToCollection } from '$lib/util/manipulateCollection';
import type { PageData } from './$types';
@ -25,6 +16,7 @@
import RemoveWishlistDialog from '$lib/components/dialog/RemoveWishlistDialog.svelte';
import { binarySearchOnStore } from '$lib/util/binarySearchOnStore';
import { convertToSavedGame } from '$lib/util/gameMapper';
import { Button } from '$components/ui/button';
$: existsInCollection = $collectionStore.find((item: SavedGameType) => item.id === game.id);
$: existsInWishlist = $wishlistStore.find((item: SavedGameType) => item.id === game.id);
@ -127,7 +119,7 @@
<iconify-icon icon={plusCircle} width="24" height="24" />
{/if}
</Button>
<Button size="md" kind={existsInWishlist ? 'danger' : 'primary'} icon on:click={onWishlistClick}>
<Button kind={existsInWishlist ? 'danger' : 'primary'} icon on:click={onWishlistClick}>
{wishlistText}
{#if existsInWishlist}
<iconify-icon icon={minusCircle} width="24" height="24" />
@ -138,7 +130,7 @@
</div>
{:else}
<span>
<a href="/auth/signup">Sign Up</a> or <a href="/auth/signin">Sign In</a> to collect this game
<Button href="/auth/signup">Sign Up</Button> or <Button href="/auth/signin">Sign In</Button> to add to a list.
</span>
{/if}
</div>

View file

@ -6,37 +6,75 @@ 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';
import type { PageServerLoad } from '../$types.js';
// import { listGameSchema } from '$lib/config/zod-schemas.js';
async function searchForGames(urlQueryParams: SearchQuery, locals) {
/**
* Asynchronous function searchForGames to fetch games from a local and remote repository based on the given parameters.
* @async
* @function searchForGames
* @param {SearchQuery} urlQueryParams - An object that represents the search parameters. It includes properties like name, min_players,
* max_players, min_playtime, max_playtime, min_age, skip, limit which are used to define the search condition for games.
* @param {any} locals - An object that contains data related to the local server environment like user information.
* @param {Function} eventFetch - A function that fetches games from the local API.
* @returns {Object} returns an object with totalCount property which is the total number of games fetched and games property which is
* an array of all the games fetched. If any error occurred during the operation, it returns an object with totalCount as 0 and games as empty array.
* @throws will throw an error if the response received from fetching games operation is not OK (200).
*/
async function searchForGames(urlQueryParams: SearchQuery, locals, eventFetch) {
try {
let games = await prisma.game.findMany({
where: {
name: {
search: urlQueryParams?.name
},
min_players: {
gte: urlQueryParams?.min_players || 0
},
max_players: {
lte: urlQueryParams?.max_players || 100
},
min_playtime: {
gte: urlQueryParams?.min_playtime || 0
},
max_playtime: {
lte: urlQueryParams?.max_playtime || 5000
},
min_age: {
gte: urlQueryParams?.min_age || 0
}
},
skip: urlQueryParams?.skip,
take: urlQueryParams?.limit,
orderBy: {
name: 'asc'
}
});
console.log('urlQueryParams search games', urlQueryParams);
// let games = await prisma.game.findMany({
// where: {
// name: {
// search: urlQueryParams?.name
// },
// min_players: {
// gte: urlQueryParams?.min_players || 0
// },
// max_players: {
// lte: urlQueryParams?.max_players || 100
// },
// min_playtime: {
// gte: urlQueryParams?.min_playtime || 0
// },
// max_playtime: {
// lte: urlQueryParams?.max_playtime || 5000
// },
// min_age: {
// gte: urlQueryParams?.min_age || 0
// }
// },
// skip: urlQueryParams?.skip,
// take: urlQueryParams?.limit,
// orderBy: {
// name: 'asc'
// }
// });
const headers: HeadersInit = new Headers();
headers.set('Content-Type', 'application/json');
const requestInit: RequestInit = {
method: 'GET',
headers
};
const response = await eventFetch(
`/api/game/search${urlQueryParams ? `?${urlQueryParams}` : ''}`,
requestInit
);
console.log('response from internal api', response);
if (!response.ok) {
console.log('Status not 200', response.status);
throw error(response.status);
}
// const games: GameType[] = [];
// let totalCount = 0;
let games = [];
if (response.ok) {
games = await response.json();
}
console.log('games from DB', games);
let totalCount = games?.length || 0;
@ -134,6 +172,17 @@ async function searchForGames(urlQueryParams: SearchQuery, locals) {
};
}
/**
* Asynchronous function createOrUpdateGame is used to create or update a game using the given game information.
*
* @async
* @function createOrUpdateGame
* @param {GameType} game - An object that holds the details about a game. It should contain required information like name, description,
* id (both internal and external), thumbnail URL, minimum age, minimum and maximum number of players, minimum and maximum play time,
* year of publication and primary publisher information including the publisher's name and ID, categories and mechanics related to the game.
*
* @returns {Promise<Object>} The return is a Promise that resolves with the data of the game that was created or updated.
*/
async function createOrUpdateGame(game: GameType) {
const categoryIds = game.categories.map((category) => ({
external_id: category.id
@ -214,19 +263,21 @@ async function createOrUpdateGame(game: GameType) {
});
}
export const load = async (event) => {
const { params, locals, request, fetch, url } = event;
export const load: PageServerLoad = async ({ params, locals, request, fetch, url }) => {
const defaults = {
limit: 10,
skip: 0
skip: 0,
order: 'asc',
sort: 'name'
};
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';
searchParams.sort = searchParams.sort || 'name';
const form = await superValidate(searchParams, search_schema);
const modifyListForm = await superValidate(listGameSchema);
// const modifyListForm = await superValidate(listGameSchema);
const queryParams: SearchQuery = {
order_by: 'rank',
@ -269,11 +320,11 @@ export const load = async (event) => {
}
const urlQueryParams = new URLSearchParams(newQueryParams);
const searchData = await searchForGames(urlQueryParams, locals);
const searchData = await searchForGames(urlQueryParams, locals, fetch);
return {
form,
modifyListForm,
// modifyListForm,
searchData
};
};