From 14d76c605ee787b6b542714f8f8ad202aeb0ae7c Mon Sep 17 00:00:00 2001 From: Ishaan Dey Date: Wed, 17 Apr 2024 22:55:02 -0400 Subject: [PATCH] auth syncing --- backend/database/src/index.ts | 33 +++++++++++++++++++++++++-------- frontend/app/(app)/layout.tsx | 33 +++++++++++++++++---------------- 2 files changed, 42 insertions(+), 24 deletions(-) diff --git a/backend/database/src/index.ts b/backend/database/src/index.ts index 42ee34d..3641987 100644 --- a/backend/database/src/index.ts +++ b/backend/database/src/index.ts @@ -20,16 +20,33 @@ export default { const db = drizzle(env.DB); - if (path === "/api/user" && method === "GET") { - const params = url.searchParams; + if (path === "/api/user") { + if (method === "GET") { + const params = url.searchParams; - if (params.has("id")) { - const id = params.get("id") as string; - const res = await db.select().from(user).where(eq(user.id, id)).get(); - return json(res ?? {}); + if (params.has("id")) { + const id = params.get("id") as string; + const res = await db.select().from(user).where(eq(user.id, id)).get(); + console.log(res); + return json(res ?? {}); + } else { + const res = await db.select().from(user).all(); + return json(res ?? {}); + } + } else if (method === "POST") { + const userSchema = z.object({ + id: z.string(), + name: z.string(), + email: z.string().email(), + }); + + const body = await request.json(); + const { id, name, email } = userSchema.parse(body); + + const res = await db.insert(user).values({ id, name, email }).returning().get(); + return json({ res }); } else { - const res = await db.select().from(user).all(); - return new Response(JSON.stringify(res)); + return new Response("Method Not Allowed", { status: 405 }); } } else return new Response("Not Found", { status: 404 }); }, diff --git a/frontend/app/(app)/layout.tsx b/frontend/app/(app)/layout.tsx index 344958d..550eea6 100644 --- a/frontend/app/(app)/layout.tsx +++ b/frontend/app/(app)/layout.tsx @@ -12,23 +12,24 @@ export default async function AppAuthLayout({ redirect("/") } - const dbUser = await fetch(`http://localhost:8787/user?id=${user.id}`) - // const dbUserJSON = await dbUser.json() + const dbUser = await fetch(`http://localhost:8787/api/user?id=${user.id}`) + const dbUserJSON = await dbUser.json() - console.log(dbUser) - - // if (!dbUserJSON) { - // const res = await fetch("http://localhost:8787/user", { - // method: "POST", - // headers: { - // "Content-Type": "application/json", - // }, - // body: JSON.stringify({ - // id: user.id, - // email: user.emailAddresses[0].emailAddress, - // }), - // }) - // } + if (!dbUserJSON?.id) { + const res = await fetch("http://localhost:8787/api/user", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + id: user.id, + name: user.firstName + " " + user.lastName, + email: user.emailAddresses[0].emailAddress, + }), + }) + } else { + // user already exists in db + } return <>{children} }