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: adding thread to the comment module #1341

Open
wants to merge 13 commits into
base: dev
Choose a base branch
from
Open
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
21 changes: 15 additions & 6 deletions src/modules/comments/comments.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { UserPayload } from './../user/interfaces/user-payload.interface';
import { User } from './../user/entities/user.entity';
import { UserPayload } from '../user/interfaces/user-payload.interface';
import { User } from '../user/entities/user.entity';
import { Controller, Body, Post, Request, Get, Param, Delete } from '@nestjs/common';
import { CommentsService } from './comments.service';
import { CreateCommentDto } from './dtos/create-comment.dto';
Expand All @@ -10,7 +10,8 @@ import { ApiBearerAuth, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagg
@ApiTags('Comments')
@Controller('comments')
export class CommentsController {
constructor(private readonly commentsService: CommentsService) {}
constructor(private readonly commentsService: CommentsService) { }

@Post('add')
@ApiOperation({ summary: 'Create a new comment' })
@ApiResponse({ status: 201, description: 'The comment has been successfully created.', type: CommentResponseDto })
Expand All @@ -21,20 +22,28 @@ export class CommentsController {
return await this.commentsService.addComment(createCommentDto, userId);
}

@Get(':id')
@ApiOperation({ summary: 'Get a comment' })
@ApiResponse({ status: 200, description: 'The comment has been retrieved successfully.' })
@Get(':id')
async getAComment(@Param('id') id: string): Promise<any> {
return await this.commentsService.getAComment(id);
}

@Get(':id/thread')
@ApiOperation({ summary: 'Get a comment thread' })
@ApiResponse({ status: 200, description: 'The comment thread has been retrieved successfully.' })
@ApiResponse({ status: 404, description: 'Comment not found.' })
async getCommentThread(@Param('id') id: string): Promise<any> {
return await this.commentsService.getCommentThread(id);
}

@ApiOperation({ summary: 'Dislike a comment' })
@ApiResponse({ status: 200, description: 'Dislike updated successfully' })
@ApiResponse({ status: 404, description: 'Comment not found' })
@Post(':id/dislike')
async dislikeComment(@Param('id') id: string, @Request() req) {
const userId = req.user.id;
// console.log('User ID:', userId); debug
// console.log('User ID:', userId); // debug (optional, kept for consistency)
return await this.commentsService.dislikeComment(id, userId);
}

Expand All @@ -44,4 +53,4 @@ export class CommentsController {
async deleteAComment(@Param('id') id: string, @Request() req): Promise<any> {
return await this.commentsService.deleteAComment(id, req.user.id);
}
}
}
42 changes: 34 additions & 8 deletions src/modules/comments/comments.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,18 @@ import { CreateCommentDto } from './dtos/create-comment.dto';
import { CommentResponseDto } from './dtos/comment-response.dto';
import { User } from '@modules/user/entities/user.entity';
import { CustomHttpException } from '@shared/helpers/custom-http-filter';

@Injectable()
export class CommentsService {
constructor(
@InjectRepository(Comment)
private readonly commentRepository: Repository<Comment>,
@InjectRepository(User)
private readonly userRepository: Repository<User>
) {}
private readonly userRepository: Repository<User>,
) { }

async addComment(createCommentDto: CreateCommentDto, userId: string): Promise<CommentResponseDto> {
const { model_id, model_type, comment } = createCommentDto;
const { model_id, model_type, comment, parentId } = createCommentDto;

if (!comment || comment.trim().length === 0) {
throw new CustomHttpException('Comment cannot be empty', HttpStatus.BAD_REQUEST);
Expand All @@ -27,18 +28,28 @@ export class CommentsService {
throw new CustomHttpException('User not found', HttpStatus.NOT_FOUND);
}

const commentedBy: string = user.first_name + ' ' + user.last_name;
let parentComment: Comment | undefined;
if (parentId) {
parentComment = await this.commentRepository.findOne({ where: { id: parentId } });
if (!parentComment) {
throw new CustomHttpException('Parent comment not found', HttpStatus.NOT_FOUND);
}
}

const Comment = this.commentRepository.create({
const newComment = this.commentRepository.create({
model_id,
model_type,
comment,
parent: parentComment, // Requires `parent_id` column in PostgreSQL
});
newComment.user = user;

const savedComment = await this.commentRepository.save(newComment); // Will fail without DB update
const commentedBy = `${user.first_name} ${user.last_name}`;

const loadComment = await this.commentRepository.save(Comment);
return {
message: 'Comment added successfully!',
savedComment: loadComment,
savedComment,
commentedBy,
};
}
Expand All @@ -54,6 +65,21 @@ export class CommentsService {
};
}


async getCommentThread(commentId: string): Promise<{ message: string; data: Comment }> {
const comment = await this.commentRepository.findOne({
where: { id: commentId },
relations: ['user', 'replies', 'replies.user'], // Requires `parent_id` column in PostgreSQL
});
if (!comment) {
throw new CustomHttpException('Comment not found', HttpStatus.NOT_FOUND);
}
return {
message: 'Comment thread retrieved successfully',
data: comment,
};
}

async deleteAComment(commentId: string, userId: string) {
const comment = await this.commentRepository.findOne({ where: { id: commentId }, relations: ['user'] });
if (!comment) {
Expand Down Expand Up @@ -105,4 +131,4 @@ export class CommentsService {
dislikeCount: comment.dislikes,
};
}
}
}
12 changes: 10 additions & 2 deletions src/modules/comments/dtos/create-comment.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IsString, IsNotEmpty } from 'class-validator';
import { IsString, IsNotEmpty, IsUUID, IsOptional } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class CreateCommentDto {
Expand All @@ -16,4 +16,12 @@ export class CreateCommentDto {
@IsString()
@IsNotEmpty()
comment: string;
}

@ApiProperty({
description: 'The ID of the parent comment (optional, for replies)',
required: false
})
@IsUUID('4') // PostgreSQL-friendly UUID v4
@IsOptional()
parentId?: string;
}
12 changes: 10 additions & 2 deletions src/modules/comments/entities/comments.entity.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Column, Entity, ManyToOne } from 'typeorm';
import { Column, Entity, ManyToOne, OneToMany } from 'typeorm';
import { AbstractBaseEntity } from '../../../entities/base.entity';
import { Product } from '../../products/entities/product.entity';
import { User } from '../../user/entities/user.entity';
Expand All @@ -20,9 +20,17 @@ export class Comment extends AbstractBaseEntity {
@Column({ nullable: true })
model_type: string;


// Threading fields for PostgreSQL
@ManyToOne(() => Comment, comment => comment.replies, { nullable: true })
parent: Comment;

@OneToMany(() => Comment, comment => comment.parent)
replies: Comment[];

@Column({ type: 'int', default: 0 }) // Add dislikes column
dislikes: number;

@Column('simple-array', { nullable: true }) // Store user IDs as an array
dislikedBy: string[];
}
}
4 changes: 3 additions & 1 deletion src/modules/products/tests/mocks/comment.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ export const mockComment: Comment = {
dislikedBy: [],
created_at: new Date(),
updated_at: new Date(),
};
parent: null, // Top-level comment has no parent
replies: [], // No replies by default
};