Moving form posts to actions slowly.

This commit is contained in:
Bradley Shellnut 2022-09-29 17:22:01 -05:00
parent a3f0d811f9
commit 0864159546
9 changed files with 313 additions and 157 deletions

13
src/app.d.ts vendored
View file

@ -1,11 +1,14 @@
/// <reference types="@sveltejs/kit" />
// See https://kit.svelte.dev/docs/types#app // See https://kit.svelte.dev/docs/types#app
// for information about these interfaces // for information about these interfaces
// and what to do when importing types // and what to do when importing types
declare namespace App { declare namespace App {
// interface Locals {} interface Locals {
userid: string;
}
// interface PageData {}
// interface PageError {}
// interface Platform {} // interface Platform {}
// interface Session {}
// interface Stuff {}
} }

View file

@ -1,23 +1,16 @@
import type { Handle } from '@sveltejs/kit'; import type { Handle } from '@sveltejs/kit';
import * as cookie from 'cookie';
export const handle: Handle = async ({ event, resolve }) => { export const handle: Handle = async ({ event, resolve }) => {
const cookies = cookie.parse(event.request.headers.get('cookie') || ''); let userid = event.cookies.get('userid');
event.locals.userid = cookies['userid'] || crypto.randomUUID();
const response = await resolve(event); if (!userid) {
if (!cookies['userid']) {
// if this is the first time the user has visited this app, // if this is the first time the user has visited this app,
// set a cookie so that we recognise them when they return // set a cookie so that we recognise them when they return
response.headers.set( userid = crypto.randomUUID();
'set-cookie', event.cookies.set('userid', userid, { path: '/' });
cookie.serialize('userid', event.locals.userid, {
path: '/',
httpOnly: true
})
);
} }
return response; event.locals.userid = userid;
return resolve(event);
}; };

View file

@ -1,3 +1,5 @@
import type { PageServerLoad, Actions } from './$types';
export const actions: Actions = { export const actions: Actions = {
default: async ({ request, locals }): Promise<any> => { default: async ({ request, locals }): Promise<any> => {
// Do things in here // Do things in here

View file

@ -1,5 +1,7 @@
<script lang="ts"> <script lang="ts">
import type { GameType, SavedGameType } from '$root/lib/types'; import { enhance, applyAction } from '$app/forms';
import type { PageData } from './$types';
import { ToastType, type GameType, type SavedGameType } from '$root/lib/types';
import { gameStore } from '$lib/stores/gameSearchStore'; import { gameStore } from '$lib/stores/gameSearchStore';
import { boredState } from '$root/lib/stores/boredState'; import { boredState } from '$root/lib/stores/boredState';
import RemoveCollectionDialog from '$root/lib/components/dialog/RemoveCollectionDialog.svelte'; import RemoveCollectionDialog from '$root/lib/components/dialog/RemoveCollectionDialog.svelte';
@ -8,7 +10,10 @@
import RandomSearch from '$lib/components/search/random/index.svelte'; import RandomSearch from '$lib/components/search/random/index.svelte';
import Random from '$lib/components/random/index.svelte'; import Random from '$lib/components/random/index.svelte';
import Pagination from '$lib/components/pagination/index.svelte'; import Pagination from '$lib/components/pagination/index.svelte';
import { toast } from '$root/lib/components/toast/toast';
export let data: PageData;
console.log('Formed data:', JSON.stringify(data));
let pageSize: number; let pageSize: number;
let currentPage: number; let currentPage: number;
$: totalItems = 0; $: totalItems = 0;
@ -85,7 +90,28 @@
Input your requirements to search for board game that match your criteria. Input your requirements to search for board game that match your criteria.
</p> </p>
<div class="game-search"> <div class="game-search">
<form on:submit|preventDefault={handleSearch} method="post"> <form
action="/search?/search"
method="post"
use:enhance={() => {
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 {
gameStore.removeAll();
gameStore.addAll(result?.data?.games);
totalItems = result?.data?.totalCount;
console.log(`Frontend result: ${JSON.stringify(result)}`);
toast.send('Sucess!', { duration: 3000, type: ToastType.INFO, dismissible: true });
await applyAction(result);
}
};
}}
>
<TextSearch showButton advancedSearch /> <TextSearch showButton advancedSearch />
</form> </form>
<section> <section>

View file

@ -0,0 +1,13 @@
<svelte:head>
<title>Bored Game | About</title>
<meta name="description" content="About Bored Game" />
</svelte:head>
<div class="content">
<h1>About Bored Game</h1>
<p>
One day we were bored and wanted to play one of our board games. Our problem was that we didn't
know which one to play.
</p>
<p>Rather than just pick one I decided to make this overcomplicated version of choice.</p>
</div>

View file

@ -0,0 +1,9 @@
import { dev } from '$app/environment';
// we don't need any JS on this page, though we'll load
// it in dev so that we get hot module replacement...
export const csr = dev;
// since there's no dynamic data here, we can prerender
// it so that it gets served as a static asset in prod
export const prerender = true;

View file

@ -0,0 +1,6 @@
import type { Actions } from '../$types';
import { Games } from '$root/search/actions';
export const actions: Actions = {
search: Games.search,
}

View file

@ -0,0 +1 @@
<h1>Search</h1>

View file

@ -1,10 +1,113 @@
import type { RequestEvent } from '@sveltejs/kit';
import { BOARD_GAME_ATLAS_CLIENT_ID } from '$env/static/private';
import type { GameType, SearchQuery } from "$root/lib/types";
import { mapAPIGameToBoredGame } from "$root/lib/util/gameMapper";
interface Actions { interface Actions {
[key: string]: any // Action [key: string]: any // Action
} }
export const Games: Actions = { export const Games: Actions = {
search: async function search({ request, locals }): Promise<any> { search: async ({ request, locals }: RequestEvent): Promise<any> => {
console.log("In search action specific")
// Do things in here
const form = await request.formData();
console.log('form', form);
const queryParams: SearchQuery = {
order_by: 'rank',
ascending: false,
limit: 20,
client_id: BOARD_GAME_ATLAS_CLIENT_ID
};
const id = form.get('id');
const ids = form.get('ids');
const minAge = form.get('minAge');
const minPlayers = form.get('minPlayers');
const maxPlayers = form.get('maxPlayers');
const exactMinAge = form.get('exactMinAge') || false;
const exactMinPlayers = form.get('exactMinPlayers') || false;
const exactMaxPlayers = form.get('exactMaxPlayers') || false;
const random = form.get('random') === 'on' || false;
if (minAge) {
if (exactMinAge) {
queryParams.min_age = +minAge;
} else {
queryParams.gt_min_age = +minAge === 1 ? 0 : +minAge - 1;
}
}
if (minPlayers) {
if (exactMinPlayers) {
queryParams.min_players = +minPlayers;
} else {
queryParams.gt_min_players = +minPlayers === 1 ? 0 : +minPlayers - 1;
}
}
if (maxPlayers) {
if (exactMaxPlayers) {
queryParams.max_players = +maxPlayers;
} else {
queryParams.lt_max_players = +maxPlayers + 1;
}
}
if (id) {
queryParams.ids = new Array(`${id}`);
}
if (ids) {
// TODO: Pass in ids array from localstorage / game store
queryParams.ids = new Array(ids);
}
queryParams.random = random;
console.log('queryParams', queryParams);
const newQueryParams: Record<string, string> = {};
for (const key in queryParams) {
newQueryParams[key] = `${queryParams[key as keyof typeof queryParams]}`;
}
const urlQueryParams = new URLSearchParams(newQueryParams);
const url = `https://api.boardgameatlas.com/api/search${urlQueryParams ? `?${urlQueryParams}` : ''
}`;
const response = await fetch(url, {
method: 'get',
headers: {
'content-type': 'application/json'
}
});
console.log('board game response', response);
if (response.status === 404) {
// user hasn't created a todo list.
// start with an empty array
return {
success: true,
games: [],
totalCount: 0
};
}
if (response.status === 200) {
const gameResponse = await response.json();
const gameList = gameResponse?.games;
const games: GameType[] = [];
gameList.forEach((game: GameType) => {
games.push(mapAPIGameToBoredGame(game));
});
console.log('games', games);
return {
success: true,
games,
totalCount: games.length
};
}
return { success: false };
} }
// create: async function create({ request, locals }): Promise<any> { // create: async function create({ request, locals }): Promise<any> {
// const data = await getFormDataObject<any>(request); // const data = await getFormDataObject<any>(request);