import { Hono } from "hono"; import { cors } from "hono/cors"; import { upgradeWebSocket, websocket } from "hono/bun"; import { DatabaseService } from "@/services/database-service"; import { RegisterRequest, RegisterResponse } from "@/types/types"; import { MESSAGES } from "@/auth/messages"; import { validateEmail } from "@/utilities/email"; import { Prisma } from "@/orm/generated/prisma/client"; import { hashPassword } from "@/utilities/password"; const app = new Hono(); app.use( "/api/v1/*", cors({ origin: "*", allowHeaders: ["X-Custom-Header", "Upgrade-Insecure-Requests"], allowMethods: ["POST", "GET", "OPTIONS"], exposeHeaders: ["Content-Length", "X-Kuma-Revision"], maxAge: 600, credentials: true, }), ); app.get("/", async (c) => { return c.json({ message: "ok", }); }); app.post("/api/v1/register", async (c) => { let body: RegisterRequest | undefined; let errors = false; let messages: Array = []; // Get the request body and handle malformed payload try { body = (await c.req.json()) as RegisterRequest; } catch (error) { console.error(`Received invalid payload: ${error}`); return c.json({ status: "error", messages: [MESSAGES.INVALID_REQUEST], } as RegisterResponse); } // ////////////////// // Request validation if (!body.email) { errors = true; messages.push(MESSAGES.MISSING_EMAIL); } if (!validateEmail(body.email)) { errors = true; messages.push(MESSAGES.INVALID_EMAIL); } if (!body.password) { errors = true; messages.push(MESSAGES.MISSING_PASSWORD); } // End: Request validation // /////////////////////// if (errors) { return c.json({ status: "error", messages: messages, } as RegisterResponse); } // Database const database = new DatabaseService(); try { // Sala la password body.password = await hashPassword(body.password); await database.getClient().user.create({ data: { ...body, first_login: true, }, }); } catch (e) { if ( e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002" ) { return c.json({ status: "error", messages: [MESSAGES.USER_ALREADY_EXISTS], } as RegisterResponse); } return c.json({ status: "error", messages: [MESSAGES.UNKNOWN_DATABASE_ERROR], } as RegisterResponse); } return c.json({ status: "success", } as RegisterResponse); }); app.get( "/ws", upgradeWebSocket((c) => { return { onOpen(e, ws) { console.log("Server: Connection opened"); ws.send("Hello!"); }, onClose: () => { console.log("Server: Connection closed"); }, onMessage: (ev) => { console.log(ev.data); }, }; }), ); export default { port: Bun.env.SERVER_PORT, fetch: app.fetch, websocket, };