Skip to content

Commit

Permalink
Merge pull request #14 from ZeitOnline/ZO-6265-fix-post
Browse files Browse the repository at this point in the history
ZO 6265: fix post
  • Loading branch information
fdiegner authored Sep 20, 2024
2 parents ff6a4d9 + 1751de6 commit 2d728bd
Show file tree
Hide file tree
Showing 8 changed files with 73 additions and 50 deletions.
19 changes: 12 additions & 7 deletions src/components/AddGameTable.svelte
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
<script lang="ts">
import { formFieldProxy, superForm, arrayProxy } from 'sveltekit-superforms';
import type { PageData } from '../routes/$types';
import GameRow from './GameRow.svelte';
import { toast } from '@zerodevx/svelte-toast';
import Separator from './Separator.svelte';
import { blur } from 'svelte/transition';
import ErrorIcon from '$components/icons/HasErrorIcon.svelte';
import IconHandler from './icons/IconHandler.svelte';
import { cubicInOut } from 'svelte/easing';
import { getHighestGameId, getNextAvailableDateForGame, updateGame } from '$lib/queries';
import { createGame, createGameQuestions, getNextAvailableDateForGame } from '$lib/queries';
import { dev } from '$app/environment';
import ViewNavigation from './ViewNavigation.svelte';
import GameCell from './GameCell.svelte';
Expand Down Expand Up @@ -52,24 +51,30 @@
// TODO: incremental ID is working, but here we are doing it like this
// because the updateGame is asking for it before
// we need to separate the logic and do different requests for games and questions
const highestId = await getHighestGameId();
const newGameId = highestId + 1;
// Construct the data for the new game
const data = {
id: newGameId,
name: $form.name,
release_date: $form.release_date,
active: $form.published,
questions: $form.questions
};
// Log the new game data to be added
console.log('Adding new game:', data);
// Send the new game data to the backend
await updateGame(newGameId, data);
const newGameArray = await createGame(data);
const newGame = newGameArray[0];
newGame.questions = $form.questions;
newGame.questions.map((question) => {
question.game_id = newGame.id;
});
const resp = await createGameQuestions(newGame);
if (!resp.ok) {
throw new Error('Failed to add questions');
}
} catch (error) {
// TODO: Error handling for conflict 409/500 etc
console.error('Error adding game:', error);
toast.push('⚠️ Failed to add the game. Please try again.', {
duration: 3000,
Expand Down
4 changes: 2 additions & 2 deletions src/components/DashboardTable.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script lang="ts">
import type { Game } from '$types';
import type { GameComplete } from '$types';
import { cubicInOut } from 'svelte/easing';
import type { ViewStateStore } from '$stores/view-state-store.svelte';
import { debounce, highlightMatch, transformedPublishedData } from '../utils';
Expand All @@ -11,7 +11,7 @@
const ITEMS_PER_PAGE = 10;
let { store, games }: { store: ViewStateStore; games: Game[] } = $props();
let { store, games }: { store: ViewStateStore; games: GameComplete[] } = $props();
let searchTerm = $state('');
let debouncedSearchTerm = $state('');
Expand Down
8 changes: 4 additions & 4 deletions src/components/EditGameTable.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@
let { store, game }: { store: ViewStateStore; game: Game } = $props();
const handleSaveEditedGame = () => {
updateGame(store.selectedGameId, {
name: (document.getElementById('name') as HTMLInputElement)?.value as string,
active: (document.getElementById('active') as HTMLInputElement)?.checked as boolean
});
// updateGame(store.selectedGameId, {
// name: (document.getElementById('name') as HTMLInputElement)?.value as string,
// active: (document.getElementById('active') as HTMLInputElement)?.checked as boolean
// });
toast.push('Game saved (Not working yet)', {
theme: {
Expand Down
66 changes: 40 additions & 26 deletions src/lib/queries.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { QuestionComplete } from "$types";
import type { Game, GameComplete, QuestionComplete } from "$types";

/**
* Url to the backend cluster.
Expand Down Expand Up @@ -48,19 +48,6 @@ export const getAllQuestionsByGameId = async (id: number) => {
return questions as QuestionComplete[]
}

/**
* Get the highest game id.
* This is mainly used to generate a new game id from this value + 1.
* @returns the highest game id
*/
export const getHighestGameId = async () => {
const response = await fetch(
`${BASE_URL}/game?select=id&order=id.desc&limit=1`
);
const data = await response.json();
return data[0].id;
}

/**
* deletes a game by its id along with all the questions associated with it and the game_state.
* @param id the id of the game to be deleted
Expand Down Expand Up @@ -142,21 +129,24 @@ export const deleteGame = async (id: number) => {
* @param data the data to be updated or created
* @returns the updated or created game
*/
export const updateGame = async (id: number, data: any) => {
export const updateGame = async (game: GameComplete) => {
// TODO: update the questions as well, here we receive only the previous ones
const questions = await getAllQuestionsByGameId(id);

if (questions.length > 0) {

// 1 - update all the questions
// upsertData('game_question', questions);
// const questions = await getAllQuestionsByGameId(game.id!);
try {
if (game.questions && game.questions.length > 0) {
// 1 - update all the questions
await upsertData('game_question', game.questions);
}

console.log("adding the new game...", game);
// 2 - update the game itself
// await upsertData('game', game);

} catch (error) {
console.error("Failed to update the game", error);
}

console.log("adding the new game...", data);
// 2 - update the game itself
await upsertData('game', data);

return data;
return game;
}

/**
Expand Down Expand Up @@ -189,4 +179,28 @@ const upsertData = async (table: string, data: any) => {
},
body: JSON.stringify(data)
});
}

export async function createGame(data: Game): Promise<GameComplete[]> {
const game = await fetch(`${BASE_URL}/game`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Prefer': 'return=representation'
},
body: JSON.stringify(data)
});
return await game.json();
}

export async function createGameQuestions(data: Game): Promise<Response> {
const { questions } = data;
const game = await fetch(`${BASE_URL}/game_question`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(questions)
});
return game;
}
10 changes: 7 additions & 3 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ export type IconOption = "create" | "delete" | "update" | "chevron" | "search" |
* This is how I game looks like
*/
export type Game = {
id: number;
name: string;
release_date: string;
active: boolean;
questions?: Question[];
}

export type Question = {
game_id?: number;
nr: number;
question: string;
answer: string;
Expand All @@ -29,9 +30,12 @@ export type Question = {
description: string;
}

export type GameComplete = Game & {
id: number;
}

export type QuestionComplete = Question & {
id: string;
game_id: string;
id: number;
}

export type Log = {
Expand Down
4 changes: 2 additions & 2 deletions src/views/DashboardView.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
import DashboardTable from '$components/DashboardTable.svelte';
import ViewNavigation from '$components/ViewNavigation.svelte';
import ViewWrapper from '$components/ViewWrapper.svelte';
import type { Game } from '$types';
import type { GameComplete } from '$types';
import type { ViewStateStore } from '../stores/view-state-store.svelte';
let { store, games }: { store: ViewStateStore; games: Game[] } = $props();
let { store, games }: { store: ViewStateStore; games: GameComplete[] } = $props();
function handleNewGameView() {
store.updateView('new-game');
Expand Down
6 changes: 3 additions & 3 deletions src/views/DeleteGameView.svelte
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<script lang="ts">
import ViewWrapper from '$components/ViewWrapper.svelte';
import type { Game } from '$types';
import type { GameComplete } from '$types';
import { toast } from '@zerodevx/svelte-toast';
import { type ViewStateStore } from '../stores/view-state-store.svelte';
import { deleteGame } from '$lib/queries';
let { store, games }: { store: ViewStateStore; games: Game[] } = $props();
let { store, games }: { store: ViewStateStore; games: GameComplete[] } = $props();
const handleBackToDashboard = () => {
store.updateView('dashboard');
Expand All @@ -31,7 +31,7 @@
}, 3500);
};
const game = games.find((game: Game) => game.id === store.selectedGameId);
const game = games.find((game: GameComplete) => game.id === store.selectedGameId);
</script>

<ViewWrapper>
Expand Down
6 changes: 3 additions & 3 deletions src/views/EditGameView.svelte
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
<script lang="ts">
import ViewWrapper from '$components/ViewWrapper.svelte';
import type { Game } from '$types';
import type { GameComplete } from '$types';
import { type ViewStateStore } from '../stores/view-state-store.svelte';
import ViewNavigation from '$components/ViewNavigation.svelte';
import EditGameTable from '$components/EditGameTable.svelte';
let { store, games }: { store: ViewStateStore; games: Game[] } = $props();
let { store, games }: { store: ViewStateStore; games: GameComplete[] } = $props();
const handleBackToDashboard = () => {
store.updateSelectedGameId(-1);
store.updateView('dashboard');
};
const game = games.find((game: Game) => game.id === store.selectedGameId);
const game = games.find((game: GameComplete) => game.id === store.selectedGameId);
if (!game) {
store.updateSelectedGameId(-1);
store.updateView('dashboard');
Expand Down

0 comments on commit 2d728bd

Please sign in to comment.