diff --git a/src/controllers/auth.controller.ts b/src/controllers/auth.controller.ts index 86cf079..1f66968 100644 --- a/src/controllers/auth.controller.ts +++ b/src/controllers/auth.controller.ts @@ -1,5 +1,36 @@ import { Request, Response } from "express"; +import { registerSchema } from "../schemas/auth.schema"; +import { auth } from "../config"; +import { z } from "zod"; +import type { Controller } from "../types"; export const helloAuth = (_req: Request, res: Response) => { res.json({ message: "hello auth" }); }; + +type RegisterSchema = z.infer; +export const register: Controller = async (req, res) => { + try { + const { name: displayName, email, password } = req.body; + + const user = await auth.createUser({ displayName, email, password }); + + res.status(201).json({ + status: "success", + message: "register success", + data: { userId: user.uid }, + }); + } catch (error) { + if (error instanceof z.ZodError) { + res.status(400).json({ + status: "fail", + message: "validation error", + errors: error.message, + }); + } + + if (error instanceof Error) { + res.status(400).json({ status: "fail", message: error.message }); + } + } +}; diff --git a/src/routes/v1/auth.route.ts b/src/routes/v1/auth.route.ts index 1bb9e26..ac55d2b 100644 --- a/src/routes/v1/auth.route.ts +++ b/src/routes/v1/auth.route.ts @@ -1,9 +1,17 @@ import { Router } from "express"; import * as authController from "@controllers/auth.controller"; +import { validator } from "../../middleware/validation.middleware"; +import { registerSchema } from "../../schemas/auth.schema"; // /api/v1/auth const authRouter = Router(); authRouter.get("/", authController.helloAuth); +authRouter.post( + "/register", + validator(registerSchema), + authController.register, +); + export default authRouter; diff --git a/src/schemas/auth.schema.ts b/src/schemas/auth.schema.ts new file mode 100644 index 0000000..14127a9 --- /dev/null +++ b/src/schemas/auth.schema.ts @@ -0,0 +1,9 @@ +import { z } from "zod"; + +export const registerSchema = z.object({ + body: z.object({ + name: z.string().min(3, "Name must be at least 3 characters"), + email: z.string().email("Invalid email address"), + password: z.string().min(8, "Password must be at least 8 characters"), + }), +});