mirror of
https://github.com/seanmorley15/AdventureLog.git
synced 2025-08-05 13:15:18 +02:00
Refactor error handling and add validation for adventure name in server and page files
This commit is contained in:
parent
d84c9f4d24
commit
88a2ac07e6
2 changed files with 27 additions and 20 deletions
|
@ -1,5 +1,5 @@
|
|||
import { lucia } from "$lib/server/auth";
|
||||
import type { RequestEvent } from "@sveltejs/kit";
|
||||
import { error, type RequestEvent } from "@sveltejs/kit";
|
||||
import { adventureTable } from "$lib/db/schema";
|
||||
import { db } from "$lib/db/db.server";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
@ -88,38 +88,35 @@ export async function POST(event: RequestEvent): Promise<Response> {
|
|||
console.log(newAdventure);
|
||||
const { name, location, date, description } = newAdventure;
|
||||
|
||||
if (!name) {
|
||||
return error(400, {
|
||||
message: "Name field is required!",
|
||||
});
|
||||
}
|
||||
|
||||
// insert the adventure to the user's visited list
|
||||
await db
|
||||
let res = await db
|
||||
.insert(adventureTable)
|
||||
.values({
|
||||
userId: event.locals.user.id,
|
||||
type: "mylog",
|
||||
name: name,
|
||||
location: location,
|
||||
date: date,
|
||||
description: description,
|
||||
location: location || null,
|
||||
date: date || null,
|
||||
description: description || null,
|
||||
})
|
||||
.returning({ insertedId: adventureTable.id })
|
||||
.execute();
|
||||
let res = await db
|
||||
.select()
|
||||
.from(adventureTable)
|
||||
.where(
|
||||
and(
|
||||
eq(adventureTable.userId, event.locals.user.id),
|
||||
eq(adventureTable.name, name),
|
||||
eq(adventureTable.location, location),
|
||||
eq(adventureTable.date, date),
|
||||
eq(adventureTable.description, description)
|
||||
)
|
||||
)
|
||||
.execute();
|
||||
|
||||
let insertedId = res[0].insertedId;
|
||||
console.log(insertedId);
|
||||
|
||||
// return a response with the adventure object values
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
adventure: { name, location, date },
|
||||
message: { message: "Adventure added" },
|
||||
id: res[0].id,
|
||||
id: insertedId,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
|
|
|
@ -78,7 +78,16 @@
|
|||
newAdventure,
|
||||
}),
|
||||
})
|
||||
.then((response) => response.json())
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
return response.json().then((data) => {
|
||||
throw new Error(
|
||||
data.error || `Failed to add adventure - ${data?.message}`
|
||||
);
|
||||
});
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
let newId = data.id;
|
||||
// add to local array for instant view update
|
||||
|
@ -100,6 +109,7 @@
|
|||
})
|
||||
.catch((error) => {
|
||||
console.error("Error:", error);
|
||||
showToast(error.message);
|
||||
});
|
||||
};
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue