feat: add comment replies and liking functionality

- Introduced support for nested comment replies in both frontend and backend.
- Added comment liking and unliking features, including like count and "isLiked" state tracking.
- Updated database schema with `parentId` and new `comment_likes` table.
- Enhanced UI for threaded comments and implemented display of like counts and reply actions.
- Refactored APIs and repositories to support replies, likes, and enriched comment data.
This commit is contained in:
Mathis HERRIOT
2026-01-29 15:26:54 +01:00
parent ed3ed66cab
commit 0976850c0c
11 changed files with 405 additions and 92 deletions

View File

@@ -8,18 +8,45 @@ import {
Req, Req,
UseGuards, UseGuards,
} from "@nestjs/common"; } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { getIronSession } from "iron-session";
import { AuthGuard } from "../auth/guards/auth.guard"; import { AuthGuard } from "../auth/guards/auth.guard";
import { getSessionOptions } from "../auth/session.config";
import type { AuthenticatedRequest } from "../common/interfaces/request.interface"; import type { AuthenticatedRequest } from "../common/interfaces/request.interface";
import { JwtService } from "../crypto/services/jwt.service";
import { CommentsService } from "./comments.service"; import { CommentsService } from "./comments.service";
import { CreateCommentDto } from "./dto/create-comment.dto"; import { CreateCommentDto } from "./dto/create-comment.dto";
@Controller() @Controller()
export class CommentsController { export class CommentsController {
constructor(private readonly commentsService: CommentsService) {} constructor(
private readonly commentsService: CommentsService,
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
) {}
@Get("contents/:contentId/comments") @Get("contents/:contentId/comments")
findAllByContentId(@Param("contentId") contentId: string) { async findAllByContentId(
return this.commentsService.findAllByContentId(contentId); @Param("contentId") contentId: string,
@Req() req: any,
) {
// Tentative de récupération de l'utilisateur pour isLiked (optionnel)
let userId: string | undefined;
try {
const session = await getIronSession<any>(
req,
req.res,
getSessionOptions(this.configService.get("SESSION_PASSWORD") as string),
);
if (session.accessToken) {
const payload = await this.jwtService.verifyJwt(session.accessToken);
userId = payload.sub;
}
} catch (_e) {
// Ignorer les erreurs de session
}
return this.commentsService.findAllByContentId(contentId, userId);
} }
@Post("contents/:contentId/comments") @Post("contents/:contentId/comments")
@@ -38,4 +65,16 @@ export class CommentsController {
const isAdmin = req.user.role === "admin" || req.user.role === "moderator"; const isAdmin = req.user.role === "admin" || req.user.role === "moderator";
return this.commentsService.remove(req.user.sub, id, isAdmin); return this.commentsService.remove(req.user.sub, id, isAdmin);
} }
@Post("comments/:id/like")
@UseGuards(AuthGuard)
like(@Req() req: AuthenticatedRequest, @Param("id") id: string) {
return this.commentsService.like(req.user.sub, id);
}
@Delete("comments/:id/like")
@UseGuards(AuthGuard)
unlike(@Req() req: AuthenticatedRequest, @Param("id") id: string) {
return this.commentsService.unlike(req.user.sub, id);
}
} }

View File

@@ -1,13 +1,15 @@
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
import { AuthModule } from "../auth/auth.module"; import { AuthModule } from "../auth/auth.module";
import { S3Module } from "../s3/s3.module";
import { CommentsController } from "./comments.controller"; import { CommentsController } from "./comments.controller";
import { CommentsService } from "./comments.service"; import { CommentsService } from "./comments.service";
import { CommentLikesRepository } from "./repositories/comment-likes.repository";
import { CommentsRepository } from "./repositories/comments.repository"; import { CommentsRepository } from "./repositories/comments.repository";
@Module({ @Module({
imports: [AuthModule], imports: [AuthModule, S3Module],
controllers: [CommentsController], controllers: [CommentsController],
providers: [CommentsService, CommentsRepository], providers: [CommentsService, CommentsRepository, CommentLikesRepository],
exports: [CommentsService], exports: [CommentsService],
}) })
export class CommentsModule {} export class CommentsModule {}

View File

@@ -3,23 +3,60 @@ import {
Injectable, Injectable,
NotFoundException, NotFoundException,
} from "@nestjs/common"; } from "@nestjs/common";
import { S3Service } from "../s3/s3.service";
import type { CreateCommentDto } from "./dto/create-comment.dto"; import type { CreateCommentDto } from "./dto/create-comment.dto";
import { CommentLikesRepository } from "./repositories/comment-likes.repository";
import { CommentsRepository } from "./repositories/comments.repository"; import { CommentsRepository } from "./repositories/comments.repository";
@Injectable() @Injectable()
export class CommentsService { export class CommentsService {
constructor(private readonly commentsRepository: CommentsRepository) {} constructor(
private readonly commentsRepository: CommentsRepository,
private readonly commentLikesRepository: CommentLikesRepository,
private readonly s3Service: S3Service,
) {}
async create(userId: string, contentId: string, dto: CreateCommentDto) { async create(userId: string, contentId: string, dto: CreateCommentDto) {
return this.commentsRepository.create({ const comment = await this.commentsRepository.create({
userId, userId,
contentId, contentId,
text: dto.text, text: dto.text,
parentId: dto.parentId,
}); });
// Enrichir le commentaire créé (pour le retour API)
return {
...comment,
likesCount: 0,
isLiked: false,
};
} }
async findAllByContentId(contentId: string) { async findAllByContentId(contentId: string, userId?: string) {
return this.commentsRepository.findAllByContentId(contentId); const comments = await this.commentsRepository.findAllByContentId(contentId);
return Promise.all(
comments.map(async (comment) => {
const [likesCount, isLiked] = await Promise.all([
this.commentLikesRepository.countByCommentId(comment.id),
userId
? this.commentLikesRepository.isLikedByUser(comment.id, userId)
: Promise.resolve(false),
]);
return {
...comment,
likesCount,
isLiked,
user: {
...comment.user,
avatarUrl: comment.user.avatarUrl
? this.s3Service.getPublicUrl(comment.user.avatarUrl)
: null,
},
};
}),
);
} }
async remove(userId: string, commentId: string, isAdmin = false) { async remove(userId: string, commentId: string, isAdmin = false) {
@@ -34,4 +71,20 @@ export class CommentsService {
await this.commentsRepository.delete(commentId); await this.commentsRepository.delete(commentId);
} }
async like(userId: string, commentId: string) {
const comment = await this.commentsRepository.findOne(commentId);
if (!comment) {
throw new NotFoundException("Comment not found");
}
await this.commentLikesRepository.addLike(commentId, userId);
}
async unlike(userId: string, commentId: string) {
const comment = await this.commentsRepository.findOne(commentId);
if (!comment) {
throw new NotFoundException("Comment not found");
}
await this.commentLikesRepository.removeLike(commentId, userId);
}
} }

View File

@@ -1,8 +1,18 @@
import { IsNotEmpty, IsString, MaxLength } from "class-validator"; import {
IsNotEmpty,
IsOptional,
IsString,
IsUUID,
MaxLength,
} from "class-validator";
export class CreateCommentDto { export class CreateCommentDto {
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
@MaxLength(1000) @MaxLength(1000)
text!: string; text!: string;
@IsOptional()
@IsUUID()
parentId?: string;
} }

View File

@@ -0,0 +1,42 @@
import { Injectable } from "@nestjs/common";
import { and, eq, sql } from "drizzle-orm";
import { DatabaseService } from "../../database/database.service";
import { commentLikes } from "../../database/schemas/comment_likes";
@Injectable()
export class CommentLikesRepository {
constructor(private readonly databaseService: DatabaseService) {}
async addLike(commentId: string, userId: string) {
await this.databaseService.db
.insert(commentLikes)
.values({ commentId, userId })
.onConflictDoNothing();
}
async removeLike(commentId: string, userId: string) {
await this.databaseService.db
.delete(commentLikes)
.where(
and(eq(commentLikes.commentId, commentId), eq(commentLikes.userId, userId)),
);
}
async countByCommentId(commentId: string) {
const results = await this.databaseService.db
.select({ count: sql<number>`count(*)` })
.from(commentLikes)
.where(eq(commentLikes.commentId, commentId));
return Number(results[0]?.count || 0);
}
async isLikedByUser(commentId: string, userId: string) {
const results = await this.databaseService.db
.select()
.from(commentLikes)
.where(
and(eq(commentLikes.commentId, commentId), eq(commentLikes.userId, userId)),
);
return !!results[0];
}
}

View File

@@ -9,11 +9,11 @@ export class CommentsRepository {
constructor(private readonly databaseService: DatabaseService) {} constructor(private readonly databaseService: DatabaseService) {}
async create(data: NewCommentInDb) { async create(data: NewCommentInDb) {
const [comment] = await this.databaseService.db const results = await this.databaseService.db
.insert(comments) .insert(comments)
.values(data) .values(data)
.returning(); .returning();
return comment; return results[0];
} }
async findAllByContentId(contentId: string) { async findAllByContentId(contentId: string) {
@@ -21,6 +21,7 @@ export class CommentsRepository {
.select({ .select({
id: comments.id, id: comments.id,
text: comments.text, text: comments.text,
parentId: comments.parentId,
createdAt: comments.createdAt, createdAt: comments.createdAt,
updatedAt: comments.updatedAt, updatedAt: comments.updatedAt,
user: { user: {
@@ -37,11 +38,11 @@ export class CommentsRepository {
} }
async findOne(id: string) { async findOne(id: string) {
const [comment] = await this.databaseService.db const results = await this.databaseService.db
.select() .select()
.from(comments) .from(comments)
.where(and(eq(comments.id, id), isNull(comments.deletedAt))); .where(and(eq(comments.id, id), isNull(comments.deletedAt)));
return comment; return results[0];
} }
async delete(id: string) { async delete(id: string) {

View File

@@ -0,0 +1,21 @@
import { pgTable, primaryKey, timestamp, uuid } from "drizzle-orm/pg-core";
import { comments } from "./comments";
import { users } from "./users";
export const commentLikes = pgTable(
"comment_likes",
{
commentId: uuid("comment_id")
.notNull()
.references(() => comments.id, { onDelete: "cascade" }),
userId: uuid("user_id")
.notNull()
.references(() => users.uuid, { onDelete: "cascade" }),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(t) => ({
pk: primaryKey({ columns: [t.commentId, t.userId] }),
}),
);

View File

@@ -12,6 +12,9 @@ export const comments = pgTable(
userId: uuid("user_id") userId: uuid("user_id")
.notNull() .notNull()
.references(() => users.uuid, { onDelete: "cascade" }), .references(() => users.uuid, { onDelete: "cascade" }),
parentId: uuid("parent_id").references(() => comments.id, {
onDelete: "cascade",
}),
text: text("text").notNull(), text: text("text").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }) createdAt: timestamp("created_at", { withTimezone: true })
.notNull() .notNull()
@@ -24,6 +27,7 @@ export const comments = pgTable(
(table) => ({ (table) => ({
contentIdIdx: index("comments_content_id_idx").on(table.contentId), contentIdIdx: index("comments_content_id_idx").on(table.contentId),
userIdIdx: index("comments_user_id_idx").on(table.userId), userIdIdx: index("comments_user_id_idx").on(table.userId),
parentIdIdx: index("comments_parent_id_idx").on(table.parentId),
}), }),
); );

View File

@@ -1,6 +1,7 @@
export * from "./api_keys"; export * from "./api_keys";
export * from "./audit_logs"; export * from "./audit_logs";
export * from "./categories"; export * from "./categories";
export * from "./comment_likes";
export * from "./comments"; export * from "./comments";
export * from "./content"; export * from "./content";
export * from "./favorites"; export * from "./favorites";

View File

@@ -2,7 +2,7 @@
import { formatDistanceToNow } from "date-fns"; import { formatDistanceToNow } from "date-fns";
import { fr } from "date-fns/locale"; import { fr } from "date-fns/locale";
import { MoreHorizontal, Send, Trash2 } from "lucide-react"; import { Heart, MoreHorizontal, Send, Trash2 } from "lucide-react";
import * as React from "react"; import * as React from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
@@ -14,6 +14,7 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"; } from "@/components/ui/dropdown-menu";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { useAuth } from "@/providers/auth-provider"; import { useAuth } from "@/providers/auth-provider";
import { type Comment, CommentService } from "@/services/comment.service"; import { type Comment, CommentService } from "@/services/comment.service";
@@ -25,6 +26,7 @@ export function CommentSection({ contentId }: CommentSectionProps) {
const { user, isAuthenticated } = useAuth(); const { user, isAuthenticated } = useAuth();
const [comments, setComments] = React.useState<Comment[]>([]); const [comments, setComments] = React.useState<Comment[]>([]);
const [newComment, setNewComment] = React.useState(""); const [newComment, setNewComment] = React.useState("");
const [replyingTo, setReplyingTo] = React.useState<Comment | null>(null);
const [isSubmitting, setIsSubmitting] = React.useState(false); const [isSubmitting, setIsSubmitting] = React.useState(false);
const [isLoading, setIsLoading] = React.useState(true); const [isLoading, setIsLoading] = React.useState(true);
@@ -49,9 +51,14 @@ export function CommentSection({ contentId }: CommentSectionProps) {
setIsSubmitting(true); setIsSubmitting(true);
try { try {
const comment = await CommentService.create(contentId, newComment.trim()); const comment = await CommentService.create(
contentId,
newComment.trim(),
replyingTo?.id,
);
setComments((prev) => [comment, ...prev]); setComments((prev) => [comment, ...prev]);
setNewComment(""); setNewComment("");
setReplyingTo(null);
toast.success("Commentaire publié !"); toast.success("Commentaire publié !");
} catch (_error) { } catch (_error) {
toast.error("Erreur lors de la publication du commentaire"); toast.error("Erreur lors de la publication du commentaire");
@@ -70,97 +77,214 @@ export function CommentSection({ contentId }: CommentSectionProps) {
} }
}; };
return ( const handleLike = async (comment: Comment) => {
<div className="space-y-6 mt-8"> if (!isAuthenticated) {
<h3 className="font-bold text-lg">Commentaires ({comments.length})</h3> toast.error("Vous devez être connecté pour liker");
return;
}
{isAuthenticated ? ( try {
<form onSubmit={handleSubmit} className="flex gap-3"> if (comment.isLiked) {
<Avatar className="h-8 w-8"> await CommentService.unlike(comment.id);
<AvatarImage src={user?.avatarUrl} /> setComments((prev) =>
<AvatarFallback>{user?.username[0].toUpperCase()}</AvatarFallback> prev.map((c) =>
c.id === comment.id
? { ...c, isLiked: false, likesCount: c.likesCount - 1 }
: c,
),
);
} else {
await CommentService.like(comment.id);
setComments((prev) =>
prev.map((c) =>
c.id === comment.id
? { ...c, isLiked: true, likesCount: c.likesCount + 1 }
: c,
),
);
}
} catch (_error) {
toast.error("Une erreur est survenue");
}
};
// Organiser les commentaires : Parents d'abord
const rootComments = comments.filter((c) => !c.parentId);
const renderComment = (comment: Comment, depth = 0) => {
const replies = comments.filter((c) => c.parentId === comment.id);
return (
<div key={comment.id} className={cn("space-y-4", depth > 0 && "ml-10")}>
<div className="flex gap-3">
<Avatar className="h-8 w-8 shrink-0">
<AvatarImage src={comment.user.avatarUrl} />
<AvatarFallback>{comment.user.username[0].toUpperCase()}</AvatarFallback>
</Avatar> </Avatar>
<div className="flex-1 space-y-2"> <div className="flex-1 space-y-1">
<Textarea <div className="flex items-center justify-between">
placeholder="Ajouter un commentaire..." <div className="flex items-center gap-2">
value={newComment} <span className="text-sm font-bold">
onChange={(e) => setNewComment(e.target.value)} {comment.user.displayName || comment.user.username}
className="min-h-[80px] resize-none" </span>
/> <span className="text-xs text-muted-foreground">
<div className="flex justify-end"> {formatDistanceToNow(new Date(comment.createdAt), {
<Button addSuffix: true,
type="submit" locale: fr,
size="sm" })}
disabled={!newComment.trim() || isSubmitting} </span>
> </div>
{isSubmitting ? "Envoi..." : "Publier"} <div className="flex items-center gap-1">
<Send className="ml-2 h-4 w-4" /> <Button
</Button> variant="ghost"
size="icon"
className={cn(
"h-8 w-8",
comment.isLiked && "text-red-500 hover:text-red-600",
)}
onClick={() => handleLike(comment)}
>
<Heart className={cn("h-4 w-4", comment.isLiked && "fill-current")} />
</Button>
{(user?.uuid === comment.user.uuid ||
user?.role === "admin" ||
user?.role === "moderator") && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => handleDelete(comment.id)}
className="text-destructive"
>
<Trash2 className="h-4 w-4 mr-2" />
Supprimer
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</div>
<p className="text-sm leading-relaxed whitespace-pre-wrap">
{comment.text}
</p>
<div className="flex items-center gap-4 pt-1">
{comment.likesCount > 0 && (
<span className="text-xs font-semibold text-muted-foreground">
{comment.likesCount} like{comment.likesCount > 1 ? "s" : ""}
</span>
)}
{isAuthenticated && depth < 1 && (
<Button
variant="ghost"
size="sm"
className="h-auto p-0 text-xs font-semibold text-muted-foreground hover:bg-transparent hover:text-foreground"
onClick={() => {
setReplyingTo(comment);
setNewComment(`@${comment.user.username} `);
document.querySelector("textarea")?.focus();
}}
>
Répondre
</Button>
)}
</div> </div>
</div> </div>
</form> </div>
{replies.length > 0 && (
<div className="space-y-4 pt-2">
{replies.map((reply) => renderComment(reply, depth + 1))}
</div>
)}
</div>
);
};
return (
<div className="space-y-6 mt-8">
<div className="flex items-center justify-between">
<h3 className="font-bold text-lg">Commentaires ({comments.length})</h3>
</div>
{isAuthenticated ? (
<div className="space-y-2">
{replyingTo && (
<div className="flex items-center justify-between bg-zinc-100 dark:bg-zinc-800 px-3 py-1.5 rounded-lg text-xs">
<span className="text-muted-foreground">
En réponse à{" "}
<span className="font-bold">@{replyingTo.user.username}</span>
</span>
<Button
variant="ghost"
size="icon"
className="h-4 w-4"
onClick={() => {
setReplyingTo(null);
setNewComment("");
}}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
)}
<form onSubmit={handleSubmit} className="flex gap-3">
<Avatar className="h-8 w-8 shrink-0">
<AvatarImage src={user?.avatarUrl} />
<AvatarFallback>{user?.username[0].toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 space-y-2">
<Textarea
placeholder={
replyingTo ? "Ajouter une réponse..." : "Ajouter un commentaire..."
}
value={newComment}
onChange={(e) => setNewComment(e.target.value)}
className="min-h-[80px] resize-none"
/>
<div className="flex justify-end gap-2">
{replyingTo && (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
setReplyingTo(null);
setNewComment("");
}}
>
Annuler
</Button>
)}
<Button
type="submit"
size="sm"
disabled={!newComment.trim() || isSubmitting}
>
{isSubmitting ? "Envoi..." : replyingTo ? "Répondre" : "Publier"}
<Send className="ml-2 h-4 w-4" />
</Button>
</div>
</div>
</form>
</div>
) : ( ) : (
<div className="bg-zinc-100 dark:bg-zinc-800 p-4 rounded-xl text-center text-sm"> <div className="bg-zinc-100 dark:bg-zinc-800 p-4 rounded-xl text-center text-sm">
Connectez-vous pour laisser un commentaire. Connectez-vous pour laisser un commentaire.
</div> </div>
)} )}
<div className="space-y-4"> <div className="space-y-6">
{isLoading ? ( {isLoading ? (
<div className="text-center text-muted-foreground py-4">Chargement...</div> <div className="text-center text-muted-foreground py-4">Chargement...</div>
) : comments.length === 0 ? ( ) : rootComments.length === 0 ? (
<div className="text-center text-muted-foreground py-4"> <div className="text-center text-muted-foreground py-4">
Aucun commentaire pour le moment. Soyez le premier ! Aucun commentaire pour le moment. Soyez le premier !
</div> </div>
) : ( ) : (
comments.map((comment) => ( rootComments.map((comment) => renderComment(comment))
<div key={comment.id} className="flex gap-3">
<Avatar className="h-8 w-8">
<AvatarImage src={comment.user.avatarUrl} />
<AvatarFallback>
{comment.user.username[0].toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 space-y-1">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<span className="text-sm font-bold">
{comment.user.displayName || comment.user.username}
</span>
<span className="text-xs text-muted-foreground">
{formatDistanceToNow(new Date(comment.createdAt), {
addSuffix: true,
locale: fr,
})}
</span>
</div>
{(user?.uuid === comment.user.uuid ||
user?.role === "admin" ||
user?.role === "moderator") && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => handleDelete(comment.id)}
className="text-destructive"
>
<Trash2 className="h-4 w-4 mr-2" />
Supprimer
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
<p className="text-sm leading-relaxed whitespace-pre-wrap">
{comment.text}
</p>
</div>
</div>
))
)} )}
</div> </div>
</div> </div>

View File

@@ -3,6 +3,9 @@ import api from "@/lib/api";
export interface Comment { export interface Comment {
id: string; id: string;
text: string; text: string;
parentId?: string;
likesCount: number;
isLiked: boolean;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
user: { user: {
@@ -19,9 +22,14 @@ export const CommentService = {
return data; return data;
}, },
async create(contentId: string, text: string): Promise<Comment> { async create(
contentId: string,
text: string,
parentId?: string,
): Promise<Comment> {
const { data } = await api.post<Comment>(`/contents/${contentId}/comments`, { const { data } = await api.post<Comment>(`/contents/${contentId}/comments`, {
text, text,
parentId,
}); });
return data; return data;
}, },
@@ -29,4 +37,12 @@ export const CommentService = {
async remove(commentId: string): Promise<void> { async remove(commentId: string): Promise<void> {
await api.delete(`/comments/${commentId}`); await api.delete(`/comments/${commentId}`);
}, },
async like(commentId: string): Promise<void> {
await api.post(`/comments/${commentId}/like`);
},
async unlike(commentId: string): Promise<void> {
await api.delete(`/comments/${commentId}/like`);
},
}; };