Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(comment Service): add delete comment functionality with authoriz… #1353

Merged
merged 2 commits into from
Mar 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/modules/comments/comments.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Controller, Body, Post, Request, Get, Param } from '@nestjs/common';
import { Controller, Body, Post, Request, Get, Param, Delete } from '@nestjs/common';
import { CommentsService } from './comments.service';
import { CreateCommentDto } from './dtos/create-comment.dto';
import { CommentResponseDto } from './dtos/comment-response.dto';
Expand All @@ -25,4 +25,11 @@ export class CommentsController {
async getAComment(@Param('id') id: string): Promise<any> {
return await this.commentsService.getAComment(id);
}

@ApiOperation({ summary: 'Delete a comment' })
@ApiResponse({ status: 200, description: 'The comment has been deleted successfully.' })
@Delete(':id/delete')
async deleteAComment(@Param('id') id: string, @Request() req): Promise<any> {
return await this.commentsService.deleteAComment(id, req.user.userId);
}
}
21 changes: 21 additions & 0 deletions src/modules/comments/comments.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,25 @@ export class CommentsService {
data: { comment },
};
}

async deleteAComment(commentId: string, userId: string) {
const comment = await this.commentRepository.findOne({ where: { id: commentId }, relations: ['user'] });
if (!comment) {
throw new CustomHttpException('Comment not found', HttpStatus.NOT_FOUND);
}

const isOwner = comment.user.id === userId;

if (!isOwner) {
throw new CustomHttpException('You are not authorized to delete this comment', HttpStatus.FORBIDDEN);
}

await this.commentRepository.delete(comment);

return {
message: 'Comment deleted successfully!',
status: HttpStatus.OK,
data: { comment },
};
}
}
55 changes: 55 additions & 0 deletions src/modules/comments/tests/comments.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import { HttpStatus } from '@nestjs/common';
const mockCommentRepository = () => ({
create: jest.fn(),
save: jest.fn(),
findOne: jest.fn(),
delete: jest.fn(),
});

const mockUserRepository = () => ({
Expand Down Expand Up @@ -75,5 +77,58 @@ describe('CommentsService', () => {
commentedBy: 'John Doe',
});
});

describe('deleteComment', () => {
it('should throw CustomHttpException if comment is not found', async () => {
commentRepository.findOne.mockResolvedValue(null);

await expect(service.deleteAComment('comment-id', 'user-id')).rejects.toThrow(CustomHttpException);
await expect(service.deleteAComment('comment-id', 'user-id')).rejects.toMatchObject({
message: 'Comment not found',
status: HttpStatus.NOT_FOUND,
});
});

it('should throw CustomHttpException if user is not the owner of the comment', async () => {
const mockOwner = { id: 'owner-id' };
const mockComment = { id: 'comment-id', user: mockOwner };

commentRepository.findOne.mockResolvedValue(mockComment);

await expect(service.deleteAComment('comment-id', 'another-user-id')).rejects.toThrow(CustomHttpException);
await expect(service.deleteAComment('comment-id', 'another-user-id')).rejects.toMatchObject({
message: 'You are not authorized to delete this comment',
status: HttpStatus.FORBIDDEN,
});
});

it('should delete a comment successfully', async () => {
const commentId = 'comment-id';
const userId = 'user-id';
const mockUser = { id: 'user-id' };
const mockComment = {
id: 'comment-id',
model_id: '1',
model_type: 'post',
comment: 'A valid comment',
user: mockUser,
};

commentRepository.findOne.mockResolvedValue(mockComment);
commentRepository.delete.mockResolvedValue(mockComment);

console.log(await commentRepository.findOne({ where: { id: commentId }, relations: ['user'] })); // Debugging

const result = await service.deleteAComment(commentId, userId);

expect(commentRepository.findOne).toHaveBeenCalledWith({ where: { id: commentId }, relations: ['user'] });
expect(commentRepository.delete).toHaveBeenCalledWith(mockComment);
expect(result).toEqual({
message: 'Comment deleted successfully!',
status: HttpStatus.OK,
data: { comment: mockComment },
});
});
});
});
});