From 3dcad530043b31c1871b1d856b9724eadd5c9bbc Mon Sep 17 00:00:00 2001 From: Sean Morley Date: Wed, 10 Apr 2024 17:54:19 +0000 Subject: [PATCH] Add clearvisits API endpoint and implement DELETE method*** ***Handle error when no id is found in DELETE method*** ***Update deleteData function in log page to use clearvisits API endpoint --- src/routes/api/clearvisits/+server.ts | 27 +++++++++++++++++++++++++++ src/routes/api/visits/+server.ts | 9 +++++++++ src/routes/log/+page.svelte | 20 +++++++++++++++++--- 3 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 src/routes/api/clearvisits/+server.ts diff --git a/src/routes/api/clearvisits/+server.ts b/src/routes/api/clearvisits/+server.ts new file mode 100644 index 0000000..64fed2f --- /dev/null +++ b/src/routes/api/clearvisits/+server.ts @@ -0,0 +1,27 @@ +import type { RequestEvent } from "@sveltejs/kit"; +import { db } from "$lib/db/db.server"; +import { eq } from "drizzle-orm"; +import { userVisitedAdventures } from "$lib/db/schema"; + +export async function DELETE(event: RequestEvent): Promise { + if (!event.locals.user) { + return new Response(JSON.stringify({ error: "No user found" }), { + status: 401, + headers: { + "Content-Type": "application/json", + }, + }); + } + let res = await db + .delete(userVisitedAdventures) + .where( + eq(userVisitedAdventures.userId, event.locals.user.id), + ) + .execute(); + return new Response(JSON.stringify({ res: res }), { + status: 200, + headers: { + "Content-Type": "application/json", + }, + }); + } \ No newline at end of file diff --git a/src/routes/api/visits/+server.ts b/src/routes/api/visits/+server.ts index 6d3bd84..72db320 100644 --- a/src/routes/api/visits/+server.ts +++ b/src/routes/api/visits/+server.ts @@ -52,6 +52,15 @@ export async function DELETE(event: RequestEvent): Promise { // get id from the body const { id } = await event.request.json(); + if (!id) { + return new Response(JSON.stringify({ error: "No id found" }), { + status: 400, + headers: { + "Content-Type": "application/json", + }, + }); + } + let res = await db .delete(userVisitedAdventures) .where( diff --git a/src/routes/log/+page.svelte b/src/routes/log/+page.svelte index ee0cfae..3aa3989 100644 --- a/src/routes/log/+page.svelte +++ b/src/routes/log/+page.svelte @@ -167,9 +167,23 @@ } function deleteData() { - clearAdventures(); - adventures = getAdventures(); - showToast("deleted"); + fetch("/api/clearvisits", { + method: "DELETE", + headers: { + "Content-Type": "application/json", + }, + }) + .then((response) => response.json()) + .then((data) => { + console.log("Success:", data); + // remove adventure from array where id matches + adventures = []; + showToast("removed"); + visitCount.set(0); + }) + .catch((error) => { + console.error("Error:", error); + }); } function removeAdventure(event: { detail: number }) {