Skip to content

Commit

Permalink
feat: improve delete game without questions
Browse files Browse the repository at this point in the history
  • Loading branch information
manuelsanchez2 committed Sep 5, 2024
1 parent 0eda3e3 commit d8b88d9
Show file tree
Hide file tree
Showing 7 changed files with 111 additions and 72 deletions.
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,11 @@ You can run some tests by using the following commands:
Check the main task on [Jira](https://zeit-online.atlassian.net/browse/ZO-5839) for further information.

- [ ] Implement the Microsoft Authentication
- [ ] POST game and questions do not work yet.
- [X] POST game
- [ ] POST questions
- [ ] Validation is required (for the moment, we can create games without questions)
- [ ] PATCH game and questions do not work as expected (they are creating instead of UPSERT) and you need to update the page to make it work.
- [ ] We have used superform in NewGameView.svelte in two forms. Do we need it also when updating game and deleting?
- [ ] DELETE game does not work as expected.
- [X] DELETE game without questions
- [ ] DELETE game with questions
- [ ] Tests for the different views need to be written.
70 changes: 37 additions & 33 deletions src/components/AddGameTable.svelte
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<script lang="ts">
import SuperDebug, { superForm } from 'sveltekit-superforms';
import { superForm } from 'sveltekit-superforms';
import type { PageData } from '../routes/$types';
import GameRow from './GameRow.svelte';
import { toast } from '@zerodevx/svelte-toast';
import { onMount } from 'svelte';
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 { updateGame } from '$lib/queries';
let {
resultsDataBody = $bindable(),
Expand All @@ -22,20 +22,35 @@
validators: false,
SPA: true,
onUpdate({ form }) {
toast.push('⭐️ Game amazingly added! Redirecting to main dashboard...', {
initial: 0,
theme: {
'--toastBackground': '#292929'
}
});
setTimeout(() => {
window.location.href = '/';
}, 3000);
// TODO: get a logic for the next ids
const randomId = Math.floor(Math.random() * 1000);
const data = {
id: randomId,
name: $form.name,
release_date: $form.release_date,
active: $form.published,
questions: resultsDataBody
};
console.log('adding ...', data);
updateGame(randomId, data);
// Successful post! Do some more client-side stuff,
// like showing a toast notification.
// console.log('toastchen here!');
// TODO: get the data from the previous form, edited and send it to the backend transformed
},
onUpdated({ form }) {
if (form.valid) {
toast.push('⭐️ Game amazingly added! Redirecting to main dashboard...', {
duration: 3000,
theme: {
'--toastBackground': '#292929'
}
});
setTimeout(() => {
window.location.href = '/';
}, 3000);
// Successful post! Do some more client-side stuff,
// like showing a toast notification.
// console.log('toastchen here!');
Expand All @@ -62,32 +77,21 @@
confirm('Are you sure you want to remove the last row?') && resultsDataBody.splice(index, 1);
}
onMount(() => {
$effect(() => {
if (resultsDataBody.length === 0) {
addRow();
}
setTimeout(() => {
form.set({
...form,
questions: {
// @ts-ignore
...form.questions,
...resultsDataBody
}
});
}, 200);
});
$effect(() => {
form.set({
...form,
questions: {
// @ts-ignore
...form.questions,
...resultsDataBody
}
});
});
// form.set({
// ...form,
// questions: {
// // @ts-ignore
// ...form.questions,
// ...resultsDataBody
// }
// });
// });
let customNameError = $state(false);
Expand Down
5 changes: 4 additions & 1 deletion src/components/DashboardTable.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@
return filteredByOptionsItems().filter((item) => {
return (
item.name.toLowerCase().includes(term) ||
item.name.toLowerCase().includes(term) ||
item.id.toString().includes(term) ||
transformedPublishedData(item.release_date).toLowerCase().includes(term)
);
});
Expand Down Expand Up @@ -212,6 +213,7 @@
<thead>
<tr>
<th class="text-nowrap">Name des Spiels</th>
<th>ID</th>
<th>Datum</th>
<th>Aktiv</th>
<th class="text-right">Aktionen</th>
Expand All @@ -222,6 +224,7 @@
{#each paginatedItems as item (item.id)}
<tr in:blur={{ duration: 300, delay: 0, easing: cubicInOut }}>
<td>{@html highlightMatch(item.name, debouncedSearchTerm)}</td>
<td>{@html highlightMatch(item.id, debouncedSearchTerm)}</td>
<td
>{@html highlightMatch(
transformedPublishedData(item.release_date),
Expand Down
4 changes: 0 additions & 4 deletions src/components/GenerateGameTable.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
if (form.valid) {
// console.log('form is valid');
// console.log('form:', form);
console.log('form csv: ', form.data.csv);
Papa.parse(form.data.csv, {
// header: true,
complete: function (results) {
Expand All @@ -41,7 +40,6 @@
return;
}
console.log('body:', body);
resultsDataBody.push(...body);
}
});
Expand All @@ -59,13 +57,11 @@
let isDragging = $state(false);
function handleDragEnter(event: DragEvent) {
console.log('we are dragging');
isDragging = true;
event.preventDefault();
}
function handleDragLeave(event: DragEvent) {
console.log('we are not dragging');
isDragging = false;
event.preventDefault();
}
Expand Down
1 change: 0 additions & 1 deletion src/components/TableSearch.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
ariaControls: string;
} = $props();
console.log('ts');
</script>

<div class="flex items-center justify-end gap-z-ds-8">
Expand Down
39 changes: 33 additions & 6 deletions src/lib/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,23 +28,34 @@ export const getAllQuestionsByGameId = async (id: number) => {
}

export const deleteGame = async (id: number) => {
// console.log("id", id);
console.log("we want to delete the game with the id: ", id);
const response = await fetch(`${BASE_URL}/game?id=eq.${id}`, {
method: 'DELETE'
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
});

return response.json();
if (!response.ok) {
throw new Error(`Failed to delete the game with id: ${id}. Status: ${response.status}`);
}

return response.statusText;
}

export const updateGame = async (id: number, data: any) => {
// TODO: update the questions as well, here we receive only the previous ones
const questions = await getAllQuestionsByGameId(id);

// 1 - update all the questions
upsertData('game_question', questions);
if(questions.length > 0) {

// 1 - update all the questions
// upsertData('game_question', questions);
}

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

return data;
}
Expand All @@ -55,6 +66,22 @@ export const updateGame = async (id: number, data: any) => {
* @param data - the data to be upserted
*/
const upsertData = async (table: string, data: any) => {
console.log('this is the table: ', table);
console.log('this is the data: ', data);

if (table == "game") {
// we need to remove the questions from the game data
const questions = data.questions;
delete data.questions;
console.log('this is the data without questions: ', data);

// we need to update the questions separately
if (questions.length > 0) {
// upsertData('game_question', questions);
}
}


await fetch(`${BASE_URL}/${table}`, {
method: 'POST',
headers: {
Expand Down
57 changes: 32 additions & 25 deletions src/views/DeleteGameView.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,40 +5,47 @@
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: Game[] } = $props();
const handleBackToDashboard = () => {
store.updateView('dashboard');
store.updateSelectedGameId(-1);
store.updateSelectedGameId(-1);
};
const handleDeleteFromList = async (id: number) => {
toast.push("Game deleted (Not working yet)", {
theme: {
'--toastBackground': '#333',
'--toastColor': '#fff',
},
});
store.updateView('dashboard');
store.updateSelectedGameId(-1);
const handleDeleteFromList = async (id: number) => {
toast.push('Deleting game...', {
duration: 3000,
theme: {
'--toastBackground': '#333',
'--toastColor': '#fff'
}
});
await deleteGame(id);
};
await deleteGame(id);
setTimeout(() => {
store.updateView('dashboard');
store.updateSelectedGameId(-1);
window.location.href = '/';
}, 3500);
};
const game = games.find((game: Game) => game.id === store.selectedGameId);
</script>

<ViewWrapper>
<div class="flex flex-col items-center gap-z-ds-14 py-z-ds-32">

{#if game !== undefined}
<div>
Are you sure you want to delete the game <strong>{game.name}</strong>?
</div>
<div class="flex justify-end gap-z-ds-8">
<button class="z-ds-button z-ds-button-outline" onclick={handleBackToDashboard}>Cancel</button>
<button class="z-ds-button" onclick={() => handleDeleteFromList(game.id)}>Delete</button>
</div>
{/if}
</div>
<div class="flex flex-col items-center gap-z-ds-14 py-z-ds-32">
{#if game !== undefined}
<div>
Are you sure you want to delete the game <strong>{game.name}</strong>?
</div>
<div class="flex justify-end gap-z-ds-8">
<button class="z-ds-button z-ds-button-outline" onclick={handleBackToDashboard}
>Cancel</button
>
<button class="z-ds-button" onclick={() => handleDeleteFromList(game.id)}>Delete</button>
</div>
{/if}
</div>
</ViewWrapper>

0 comments on commit d8b88d9

Please sign in to comment.