move to routes{} declaration, move db to util, add example api invocations

This commit is contained in:
Badtz 2025-06-30 20:47:36 -07:00
parent 040fa2637d
commit ce44469e3a
2 changed files with 48 additions and 19 deletions

21
src/db/util.ts Normal file
View file

@ -0,0 +1,21 @@
import { Database } from "bun:sqlite";
import { drizzle } from "drizzle-orm/bun-sqlite";
import { eq } from "drizzle-orm";
import { usersTable } from "./schema";
export const db = drizzle(new Database(process.env.DB_FILE_NAME!));
export async function createUser(name: string, age: number, email: string) {
const user: typeof usersTable.$inferInsert = {
name,
age,
email,
};
await db.insert(usersTable).values(user);
return user;
}
export async function getUser(email: string) {
return await db.select().from(usersTable).where(eq(usersTable.email, email));
}

View file

@ -1,22 +1,30 @@
import { Database } from "bun:sqlite";
import { drizzle } from "drizzle-orm/bun-sqlite";
const port = Number(process.env.PORT) || 3000;
const db = drizzle(new Database(process.env.DB_FILE_NAME!));
const server = Bun.serve({
port,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/") {
return new Response("landing page", { status: 200 });
}
if (url.pathname.startsWith("/public/")) {
const filePath = `./src/public${url.pathname.slice(7)}`;
import { createUser, getUser } from "./db/util";
Bun.serve({
port: Number(process.env.PORT) || 3000,
routes: {
"/": (req) => {
return new Response("Welcome to the landing page!", { status: 200 });
},
"/public/*": (req) => {
const filePath = `./src/public${req.url.slice(7)}`;
if (Bun.file(filePath).size) return new Response(Bun.file(filePath));
return new Response("Not Found", { status: 404 });
}
return new Response("Not Found", { status: 404 });
return new Response("File not found", { status: 404 });
},
"/api/users/:email": async (req) => {
const users = await getUser(req.params.email);
return Response.json(users);
},
"/api/create": () => {
return Response.json(
createUser("Badtz", 27, "me@badtz.dev").then((user) =>
JSON.stringify(user)
)
);
},
},
fetch(req): Response {
return new Response("Page not found.", {
status: 404,
});
},
});