From c8cb5d16d1454afcffd0d46fb4b254001685777b Mon Sep 17 00:00:00 2001 From: gibbyb Date: Mon, 9 Sep 2024 23:03:48 -0500 Subject: [PATCH] Add api to get users for initial app start --- src/app/api/getUsers/route.ts | 21 +++++++++++++++++++++ src/server/functions.ts | 14 ++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 src/app/api/getUsers/route.ts diff --git a/src/app/api/getUsers/route.ts b/src/app/api/getUsers/route.ts new file mode 100644 index 0000000..9d08c23 --- /dev/null +++ b/src/app/api/getUsers/route.ts @@ -0,0 +1,21 @@ +'use server'; +import { NextResponse } from 'next/server'; +import { getUsers } from '~/server/functions'; + +export const GET = async (request: Request) => { + try { + const url = new URL(request.url); + const apiKey = url.searchParams.get('apiKey'); + if (apiKey !== process.env.API_KEY) { + console.log('Invalid API Key'); + return NextResponse.json({ message: "Invalid API Key" }, { status: 401 }); + } else { + const users = await getUsers(); + return NextResponse.json(users); + } + } catch (error) { + console.error(error); + return NextResponse.json({ message: "Error" }, { status: 500 }); + } +}; +// localhost:3000/api/getUsers?apiKey=I_Love_Madeline diff --git a/src/server/functions.ts b/src/server/functions.ts index 8cd89bd..d0d8dc7 100755 --- a/src/server/functions.ts +++ b/src/server/functions.ts @@ -3,6 +3,20 @@ import { db } from '~/server/db'; import * as schema from '~/server/db/schema'; import { eq } from 'drizzle-orm'; +export const getUsers = async () => { + try { + const result = await db.select({ + id: schema.users.id, + name: schema.users.name, + message: schema.users.message, + }).from(schema.users); + return result; + } catch (error) { + console.error("Error fetching users", error); + throw new Error("Failed to fetch users"); + } +}; + export const getMessage = async (userId: number) => { try { let message = 1;