Skip to content

Commit

Permalink
create update profile endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
rafa-lopes-pt committed Jun 23, 2024
1 parent 980b3fd commit 51d0904
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 3 deletions.
12 changes: 12 additions & 0 deletions backend/src/routes/controllers/account/UpdateProfile.schema.ts
Original file line number Diff line number Diff line change
@@ -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<typeof UpdateProfileSchema>;
13 changes: 10 additions & 3 deletions backend/src/routes/controllers/account/account.router.ts
Original file line number Diff line number Diff line change
@@ -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;
41 changes: 41 additions & 0 deletions backend/src/routes/controllers/account/updateProfile.controller.ts
Original file line number Diff line number Diff line change
@@ -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);
}
}

0 comments on commit 51d0904

Please sign in to comment.