diff --git a/backend/src/routes/controllers/account/UpdateProfile.schema.ts b/backend/src/routes/controllers/account/UpdateProfile.schema.ts new file mode 100644 index 0000000..1b90837 --- /dev/null +++ b/backend/src/routes/controllers/account/UpdateProfile.schema.ts @@ -0,0 +1,12 @@ +import { UserSchema } from "../../../../../shared/schemas/user.schema"; +import z from "zod"; + +const UpdateProfileSchema = UserSchema.partial() + .omit({ email: true }) + .refine((data) => Object.keys(data).some((e) => e), { + message: "Requires at least one field to update", + path: [""], + }); +export default UpdateProfileSchema; + +export type UpdateProfileSchemaType = z.infer; diff --git a/backend/src/routes/controllers/account/account.router.ts b/backend/src/routes/controllers/account/account.router.ts index 72bf5b6..4821d00 100644 --- a/backend/src/routes/controllers/account/account.router.ts +++ b/backend/src/routes/controllers/account/account.router.ts @@ -1,10 +1,17 @@ import express from "express"; import authMiddleware from "../../middleware/auth.middleware"; +import createBodyValidatorMiddleware from "../../middleware/createBodyValidator.middleware"; +import UpdateProfileSchema from "./UpdateProfile.schema"; +import updateProfileController from "./updateProfile.controller"; const router = express.Router(); -router.get("/test", authMiddleware, (_, res) => { - res.status(200).json(); -}); +router.use(authMiddleware); + +router.put( + "/profile", + createBodyValidatorMiddleware(UpdateProfileSchema), + updateProfileController +); export default router; diff --git a/backend/src/routes/controllers/account/updateProfile.controller.ts b/backend/src/routes/controllers/account/updateProfile.controller.ts new file mode 100644 index 0000000..19ea3cb --- /dev/null +++ b/backend/src/routes/controllers/account/updateProfile.controller.ts @@ -0,0 +1,41 @@ +import { NextFunction, Request, Response } from "express"; +import HTTPCodes from "simple-http-codes"; +import UserRepository from "../../../repositories/User.repository"; +import HttpError from "../../../utils/HttpError"; +import { UpdateProfileSchemaType } from "./UpdateProfile.schema"; + +export default async function updateProfileController( + req: Request, + res: Response, + next: NextFunction +) { + const dataToUpdate = req.body as UpdateProfileSchemaType; + + if (!dataToUpdate) { + return res + .status(HTTPCodes.ClientError.BAD_REQUEST) + .json({ message: "missing fields to update" }); + } + + try { + const db_response = await UserRepository.update( + { email: res.locals.email }, + dataToUpdate + ); + + if (db_response.error) { + throw new HttpError("BAD_GATEWAY", db_response.message, { + error: db_response.error, + context: "updating user profile info", + cause: "repository update method", + }); + } + + if (db_response.data) { + const { _id: _id, password: _password, ...user } = db_response.data; + return res.status(HTTPCodes.Success.OK).json({ user }); + } + } catch (error) { + next(error); + } +}