Skip to content

Commit

Permalink
update profile
Browse files Browse the repository at this point in the history
  • Loading branch information
Dawaic6 committed May 27, 2024
1 parent d468193 commit 2240572
Show file tree
Hide file tree
Showing 6 changed files with 233 additions and 3 deletions.
82 changes: 81 additions & 1 deletion src/__test__/userController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,4 +414,84 @@ describe('Get All Users Tests', () => {
expect(response.status).toBe(200);
expect(response.body.message).toEqual('All users deleted successfully');
});
});
});
describe('update user Profile', () => {
interface IUser {
id: number;
firstName: string;
lastName: string;
email: string;
password?: string;
userType?: Role;
googleId?: string;
facebookId?: string;
picture?: string;
provider?: string;
isVerified: boolean;
twoFactorCode?: number;
}

interface Role {
id: number;
name: string;
permissions: string[];
}


let user: IUser | undefined | null;
const userData = {
firstName: 'jan',
lastName: 'bosco',
email: 'bosco@gmail.com',
password: 'boscoPassword123',
};

beforeEach(async () => {

await request(app).post('/api/v1/register').send(userData);
user = await userRepository.findOne({ where: { email: userData.email } });
});

it('should update the user profile successfully', async () => {
if (user) {
const newUserData = {
firstName: 'NewFirstName',
lastName: 'NewLastName',
email: 'newemail@example.com',
password: 'bosco@gmail.com',
};

const response = await request(app)
.put(`/api/v1/updateProfile/${user?.id}`)
.send(newUserData);
expect(response.statusCode).toBe(201);
expect(response.body.message).toBe('User updated successfully');
}
});

it('should return 404 when user not found', async () => {
const Id = 999;
const response = await request(app)
.put(`/api/v1/updateProfile/${Id}`)
.send(userData);
expect(response.statusCode).toBe(404);
expect(response.body.error).toBe('User not found');
});

it('should return 400 when email already exists', async () => {
if (user) {
const newUserData = {
firstName: 'NewFirstName',
lastName: 'NewLastName',
email: 'newemail@example.com',
password: 'bosco@gmail.com',
};

const response = await request(app)
.put(`/api/v1/updateProfile/${user.id}`)
.send(newUserData);
expect(response.statusCode).toBe(400);
expect(response.body.error).toBe('Email is already taken');
}
});
});
39 changes: 38 additions & 1 deletion src/controller/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { sendCode } from '../emails/mailer';
import jwt from 'jsonwebtoken';
import errorHandler from '../middlewares/errorHandler';


// Assuming dbConnection.getRepository(UserModel) returns a repository instance
const userRepository = dbConnection.getRepository(UserModel);
const roleRepository = dbConnection.getRepository(Role);
Expand All @@ -21,6 +22,14 @@ interface CreateUserRequestBody {
userType: 'Admin' | 'vendor' | 'buyer';
}

interface UpdateRrofileRequestBody {
firstName: string;
lastName: string;
email: string;
password:string;
}


// Define validation and sanitization rules
const registerUserRules = [
check('firstName').isLength({ min: 1 }).withMessage('First name is required'),
Expand Down Expand Up @@ -265,4 +274,32 @@ await userRepository.save(user);

return res.status(200).json({ message: 'Password updated successfully' });

});
});
export const updateProfile = errorHandler(async (req: Request, res: Response) => {
const userId: number = parseInt(req.params.id);
const { firstName, lastName, email } = req.body as UpdateRrofileRequestBody;

const user = await userRepository.findOne({ where: { id: userId } });

if (!user) {
return res.status(404).json({ error: 'User not found' });
}

user.firstName = firstName || user.firstName;
user.lastName = lastName || user.lastName;


const emailExists = await userRepository.findOne({ where: { email } });

if (emailExists) {
return res.status(400).json({ error: 'Email is already taken' });
}

user.email = email;



await userRepository.save(user);

return res.status(201).json({ message: 'User updated successfully' });
});
33 changes: 33 additions & 0 deletions src/database/models/reviewEntitiy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, JoinColumn } from "typeorm";
import UserModel from "./userModel";
import Product from "./productEntity";

@Entity()
export default class Review {
@PrimaryGeneratedColumn()
id: number;
@Column({nullable: true})
userId:number ;

@Column({nullable:true})
productId: number;

@Column()
feedBack: string;

@Column()
ratings: number;

// @ManyToOne(() => UserModel, user => user.reviews)
// @JoinColumn({ name: "userId" })
// user: UserModel; // Use UserModel instead of User

// @ManyToOne(() => Product, product => product.reviews)
// @JoinColumn({ name: "productId" })
// product: Product;
@ManyToOne(() => UserModel, { onDelete: 'CASCADE', onUpdate: 'CASCADE' })
user: UserModel;

@ManyToOne(() => Product, { onDelete: 'CASCADE', onUpdate: 'CASCADE' })
product: Product;
}
Empty file.
79 changes: 78 additions & 1 deletion src/docs/userRegisterDocs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,83 @@
* type: string
* description: An error message indicating a server error
*/

/**
* @swagger
* /api/v1/updateProfile/{id}:
* put:
* summary: Update user profile
* tags:
* - User
* parameters:
* - in: path
* name: id
* required: true
* description: ID of the user to update
* schema:
* type: integer
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* firstName:
* type: string
* description: The updated first name of the user.
* lastName:
* type: string
* description: The updated last name of the user.
* email:
* type: string
* format: email
* description: The updated email address of the user.
* responses:
* '200':
* description: User profile updated successfully.
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
* description: A message indicating successful profile update.
* '400':
* description: Bad request or validation errors.
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* description: Error message indicating the reason for the bad request.
* '404':
* description: Not Found - User not found.
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* description: A message indicating the user was not found.
* '500':
* description: Internal server error.
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* description: A message indicating an internal server error occurred.
*/



/**
* @swagger
* /api/v1/user/recover/confirm:
Expand Down Expand Up @@ -275,4 +352,4 @@
* message:
* type: string
* description: An error message indicating a server error
*/
*/
3 changes: 3 additions & 0 deletions src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
updateNewPassword,
getAllUsers,
deleteAllUsers,
updateProfile,
} from '../controller/userController';

import {
Expand Down Expand Up @@ -39,4 +40,6 @@ userRouter.put(
);
userRouter.post('/recover', recoverPassword);
userRouter.put('/recover/confirm', updateNewPassword)

userRouter.put('/updateProfile/:id',updateProfile);
export default userRouter;

0 comments on commit 2240572

Please sign in to comment.