8 Commits

Author SHA1 Message Date
Mathis HERRIOT
ace438be6b chore: bump version to 1.8.2
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 1m39s
CI/CD Pipeline / Valider frontend (push) Successful in 1m43s
CI/CD Pipeline / Valider documentation (push) Successful in 1m47s
CI/CD Pipeline / Déploiement en Production (push) Successful in 5m33s
2026-01-29 15:33:51 +01:00
Mathis HERRIOT
ea1afa7688 test: add unit tests for comment liking and enriched comment data
- Added tests for comment liking (`like` and `unlike` methods).
- Improved `findAllByContentId` tests to cover enriched comment data (likes count, isLiked, and user avatar URL resolution).
- Mocked new dependencies (`CommentLikesRepository` and `S3Service`) in `CommentsService` unit tests.
2026-01-29 15:30:20 +01:00
Mathis HERRIOT
0976850c0c 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.
2026-01-29 15:26:54 +01:00
Mathis HERRIOT
ed3ed66cab feat: add database snapshot for schema changes
- Created a snapshot to reflect the updated database schema, including new tables `api_keys`, `audit_logs`, `categories`, `comments`, `contents`, and related relationships.
- Includes indexes, unique constraints, and foreign key definitions.
2026-01-29 15:26:09 +01:00
Mathis HERRIOT
46ffdd809c chore: bump version to 1.8.1
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 1m36s
CI/CD Pipeline / Valider frontend (push) Successful in 1m41s
CI/CD Pipeline / Valider documentation (push) Successful in 1m45s
CI/CD Pipeline / Déploiement en Production (push) Successful in 5m30s
2026-01-29 15:11:01 +01:00
Mathis HERRIOT
2dcd277347 test: rename variables and format multiline assertions in messages service spec
- Renamed `repository` and `eventsGateway` to `_repository` and `_eventsGateway` to follow conventions for unused test variables.
- Reformatted multiline assertions for better readability.
2026-01-29 15:10:56 +01:00
Mathis HERRIOT
9486803aeb test: rename variables and format multiline assertion in events gateway spec
- Renamed `jwtService` to `_jwtService` to align with conventions for unused test variables.
- Adjusted multiline assertion formatting for improved readability.
2026-01-29 15:10:43 +01:00
Mathis HERRIOT
1e0bb03182 test: format multiline assertion in comments service spec
- Adjusted `remove` test to improve readability of multiline assertion.
2026-01-29 15:10:22 +01:00
20 changed files with 2631 additions and 114 deletions

View File

@@ -0,0 +1,54 @@
CREATE TABLE "comment_likes" (
"comment_id" uuid NOT NULL,
"user_id" uuid NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "comment_likes_comment_id_user_id_pk" PRIMARY KEY("comment_id","user_id")
);
--> statement-breakpoint
CREATE TABLE "comments" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"content_id" uuid NOT NULL,
"user_id" uuid NOT NULL,
"parent_id" uuid,
"text" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
"deleted_at" timestamp with time zone
);
--> statement-breakpoint
CREATE TABLE "conversation_participants" (
"conversation_id" uuid NOT NULL,
"user_id" uuid NOT NULL,
"joined_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "conversation_participants_conversation_id_user_id_pk" PRIMARY KEY("conversation_id","user_id")
);
--> statement-breakpoint
CREATE TABLE "conversations" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "messages" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"conversation_id" uuid NOT NULL,
"sender_id" uuid NOT NULL,
"text" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"read_at" timestamp with time zone
);
--> statement-breakpoint
ALTER TABLE "comment_likes" ADD CONSTRAINT "comment_likes_comment_id_comments_id_fk" FOREIGN KEY ("comment_id") REFERENCES "public"."comments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "comment_likes" ADD CONSTRAINT "comment_likes_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "comments" ADD CONSTRAINT "comments_content_id_contents_id_fk" FOREIGN KEY ("content_id") REFERENCES "public"."contents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "comments" ADD CONSTRAINT "comments_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "comments" ADD CONSTRAINT "comments_parent_id_comments_id_fk" FOREIGN KEY ("parent_id") REFERENCES "public"."comments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "conversation_participants" ADD CONSTRAINT "conversation_participants_conversation_id_conversations_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "public"."conversations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "conversation_participants" ADD CONSTRAINT "conversation_participants_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "messages" ADD CONSTRAINT "messages_conversation_id_conversations_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "public"."conversations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "messages" ADD CONSTRAINT "messages_sender_id_users_uuid_fk" FOREIGN KEY ("sender_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "comments_content_id_idx" ON "comments" USING btree ("content_id");--> statement-breakpoint
CREATE INDEX "comments_user_id_idx" ON "comments" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "comments_parent_id_idx" ON "comments" USING btree ("parent_id");--> statement-breakpoint
CREATE INDEX "messages_conversation_id_idx" ON "messages" USING btree ("conversation_id");--> statement-breakpoint
CREATE INDEX "messages_sender_id_idx" ON "messages" USING btree ("sender_id");

File diff suppressed because it is too large Load Diff

View File

@@ -57,6 +57,13 @@
"when": 1769605995410, "when": 1769605995410,
"tag": "0007_melodic_synch", "tag": "0007_melodic_synch",
"breakpoints": true "breakpoints": true
},
{
"idx": 8,
"version": "7",
"when": 1769696731978,
"tag": "0008_bitter_darwin",
"breakpoints": true
} }
] ]
} }

View File

@@ -1,6 +1,6 @@
{ {
"name": "@memegoat/backend", "name": "@memegoat/backend",
"version": "1.8.0", "version": "1.8.2",
"description": "", "description": "",
"author": "", "author": "",
"private": true, "private": true,

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

@@ -1,6 +1,8 @@
import { ForbiddenException, NotFoundException } from "@nestjs/common"; import { ForbiddenException, NotFoundException } from "@nestjs/common";
import { Test, TestingModule } from "@nestjs/testing"; import { Test, TestingModule } from "@nestjs/testing";
import { S3Service } from "../s3/s3.service";
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";
describe("CommentsService", () => { describe("CommentsService", () => {
@@ -14,11 +16,25 @@ describe("CommentsService", () => {
delete: jest.fn(), delete: jest.fn(),
}; };
const mockCommentLikesRepository = {
addLike: jest.fn(),
removeLike: jest.fn(),
countByCommentId: jest.fn(),
isLikedByUser: jest.fn(),
};
const mockS3Service = {
getPublicUrl: jest.fn(),
};
beforeEach(async () => { beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({ const module: TestingModule = await Test.createTestingModule({
providers: [ providers: [
CommentsService, CommentsService,
{ provide: CommentsRepository, useValue: mockCommentsRepository }, { provide: CommentsRepository, useValue: mockCommentsRepository },
{ provide: CommentLikesRepository, useValue: mockCommentLikesRepository },
{ provide: S3Service, useValue: mockS3Service },
], ],
}).compile(); }).compile();
@@ -34,7 +50,7 @@ describe("CommentsService", () => {
it("should create a comment", async () => { it("should create a comment", async () => {
const userId = "user1"; const userId = "user1";
const contentId = "content1"; const contentId = "content1";
const dto = { text: "Nice meme" }; const dto = { text: "Nice meme", parentId: undefined };
mockCommentsRepository.create.mockResolvedValue({ id: "c1", ...dto }); mockCommentsRepository.create.mockResolvedValue({ id: "c1", ...dto });
const result = await service.create(userId, contentId, dto); const result = await service.create(userId, contentId, dto);
@@ -43,16 +59,25 @@ describe("CommentsService", () => {
userId, userId,
contentId, contentId,
text: dto.text, text: dto.text,
parentId: undefined,
}); });
}); });
}); });
describe("findAllByContentId", () => { describe("findAllByContentId", () => {
it("should return comments for a content", async () => { it("should return comments for a content", async () => {
mockCommentsRepository.findAllByContentId.mockResolvedValue([{ id: "c1" }]); mockCommentsRepository.findAllByContentId.mockResolvedValue([
const result = await service.findAllByContentId("content1"); { id: "c1", user: { avatarUrl: "path" } },
]);
mockCommentLikesRepository.countByCommentId.mockResolvedValue(5);
mockCommentLikesRepository.isLikedByUser.mockResolvedValue(true);
mockS3Service.getPublicUrl.mockReturnValue("url");
const result = await service.findAllByContentId("content1", "u1");
expect(result).toHaveLength(1); expect(result).toHaveLength(1);
expect(repository.findAllByContentId).toHaveBeenCalledWith("content1"); expect(result[0].likesCount).toBe(5);
expect(result[0].isLiked).toBe(true);
expect(result[0].user.avatarUrl).toBe("url");
}); });
}); });
@@ -76,7 +101,28 @@ describe("CommentsService", () => {
it("should throw ForbiddenException if not owner and not admin", async () => { it("should throw ForbiddenException if not owner and not admin", async () => {
mockCommentsRepository.findOne.mockResolvedValue({ userId: "u1" }); mockCommentsRepository.findOne.mockResolvedValue({ userId: "u1" });
await expect(service.remove("other", "c1")).rejects.toThrow(ForbiddenException); await expect(service.remove("other", "c1")).rejects.toThrow(
ForbiddenException,
);
});
});
describe("like", () => {
it("should add like", async () => {
mockCommentsRepository.findOne.mockResolvedValue({ id: "c1" });
await service.like("u1", "c1");
expect(mockCommentLikesRepository.addLike).toHaveBeenCalledWith("c1", "u1");
});
});
describe("unlike", () => {
it("should remove like", async () => {
mockCommentsRepository.findOne.mockResolvedValue({ id: "c1" });
await service.unlike("u1", "c1");
expect(mockCommentLikesRepository.removeLike).toHaveBeenCalledWith(
"c1",
"u1",
);
}); });
}); });
}); });

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

@@ -6,8 +6,8 @@ import { MessagesRepository } from "./repositories/messages.repository";
describe("MessagesService", () => { describe("MessagesService", () => {
let service: MessagesService; let service: MessagesService;
let repository: MessagesRepository; let _repository: MessagesRepository;
let eventsGateway: EventsGateway; let _eventsGateway: EventsGateway;
const mockMessagesRepository = { const mockMessagesRepository = {
findConversationBetweenUsers: jest.fn(), findConversationBetweenUsers: jest.fn(),
@@ -33,28 +33,39 @@ describe("MessagesService", () => {
}).compile(); }).compile();
service = module.get<MessagesService>(MessagesService); service = module.get<MessagesService>(MessagesService);
repository = module.get<MessagesRepository>(MessagesRepository); _repository = module.get<MessagesRepository>(MessagesRepository);
eventsGateway = module.get<EventsGateway>(EventsGateway); _eventsGateway = module.get<EventsGateway>(EventsGateway);
}); });
describe("sendMessage", () => { describe("sendMessage", () => {
it("should send message to existing conversation", async () => { it("should send message to existing conversation", async () => {
const senderId = "s1"; const senderId = "s1";
const dto = { recipientId: "r1", text: "hello" }; const dto = { recipientId: "r1", text: "hello" };
mockMessagesRepository.findConversationBetweenUsers.mockResolvedValue({ id: "conv1" }); mockMessagesRepository.findConversationBetweenUsers.mockResolvedValue({
mockMessagesRepository.createMessage.mockResolvedValue({ id: "m1", text: "hello" }); id: "conv1",
});
mockMessagesRepository.createMessage.mockResolvedValue({
id: "m1",
text: "hello",
});
const result = await service.sendMessage(senderId, dto); const result = await service.sendMessage(senderId, dto);
expect(result.id).toBe("m1"); expect(result.id).toBe("m1");
expect(mockEventsGateway.sendToUser).toHaveBeenCalledWith("r1", "new_message", expect.anything()); expect(mockEventsGateway.sendToUser).toHaveBeenCalledWith(
"r1",
"new_message",
expect.anything(),
);
}); });
it("should create new conversation if not exists", async () => { it("should create new conversation if not exists", async () => {
const senderId = "s1"; const senderId = "s1";
const dto = { recipientId: "r1", text: "hello" }; const dto = { recipientId: "r1", text: "hello" };
mockMessagesRepository.findConversationBetweenUsers.mockResolvedValue(null); mockMessagesRepository.findConversationBetweenUsers.mockResolvedValue(null);
mockMessagesRepository.createConversation.mockResolvedValue({ id: "new_conv" }); mockMessagesRepository.createConversation.mockResolvedValue({
id: "new_conv",
});
mockMessagesRepository.createMessage.mockResolvedValue({ id: "m1" }); mockMessagesRepository.createMessage.mockResolvedValue({ id: "m1" });
await service.sendMessage(senderId, dto); await service.sendMessage(senderId, dto);
@@ -67,7 +78,9 @@ describe("MessagesService", () => {
describe("getMessages", () => { describe("getMessages", () => {
it("should return messages if user is participant", async () => { it("should return messages if user is participant", async () => {
mockMessagesRepository.isParticipant.mockResolvedValue(true); mockMessagesRepository.isParticipant.mockResolvedValue(true);
mockMessagesRepository.findMessagesByConversationId.mockResolvedValue([{ id: "m1" }]); mockMessagesRepository.findMessagesByConversationId.mockResolvedValue([
{ id: "m1" },
]);
const result = await service.getMessages("u1", "conv1"); const result = await service.getMessages("u1", "conv1");
expect(result).toHaveLength(1); expect(result).toHaveLength(1);
@@ -75,7 +88,9 @@ describe("MessagesService", () => {
it("should throw ForbiddenException if user is not participant", async () => { it("should throw ForbiddenException if user is not participant", async () => {
mockMessagesRepository.isParticipant.mockResolvedValue(false); mockMessagesRepository.isParticipant.mockResolvedValue(false);
await expect(service.getMessages("u1", "conv1")).rejects.toThrow(ForbiddenException); await expect(service.getMessages("u1", "conv1")).rejects.toThrow(
ForbiddenException,
);
}); });
}); });
}); });

View File

@@ -1,12 +1,11 @@
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import { Test, TestingModule } from "@nestjs/testing"; import { Test, TestingModule } from "@nestjs/testing";
import { Server } from "socket.io";
import { JwtService } from "../crypto/services/jwt.service"; import { JwtService } from "../crypto/services/jwt.service";
import { EventsGateway } from "./events.gateway"; import { EventsGateway } from "./events.gateway";
describe("EventsGateway", () => { describe("EventsGateway", () => {
let gateway: EventsGateway; let gateway: EventsGateway;
let jwtService: JwtService; let _jwtService: JwtService;
const mockJwtService = { const mockJwtService = {
verifyJwt: jest.fn(), verifyJwt: jest.fn(),
@@ -26,7 +25,7 @@ describe("EventsGateway", () => {
}).compile(); }).compile();
gateway = module.get<EventsGateway>(EventsGateway); gateway = module.get<EventsGateway>(EventsGateway);
jwtService = module.get<JwtService>(JwtService); _jwtService = module.get<JwtService>(JwtService);
gateway.server = { gateway.server = {
to: jest.fn().mockReturnThis(), to: jest.fn().mockReturnThis(),
emit: jest.fn(), emit: jest.fn(),
@@ -46,7 +45,10 @@ describe("EventsGateway", () => {
gateway.sendToUser(userId, event, data); gateway.sendToUser(userId, event, data);
expect(gateway.server.to).toHaveBeenCalledWith(`user:${userId}`); expect(gateway.server.to).toHaveBeenCalledWith(`user:${userId}`);
expect(gateway.server.to(`user:${userId}`).emit).toHaveBeenCalledWith(event, data); expect(gateway.server.to(`user:${userId}`).emit).toHaveBeenCalledWith(
event,
data,
);
}); });
}); });
}); });

View File

@@ -1,6 +1,6 @@
{ {
"name": "@memegoat/frontend", "name": "@memegoat/frontend",
"version": "1.8.0", "version": "1.8.2",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",

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`);
},
}; };

View File

@@ -1,6 +1,6 @@
{ {
"name": "@memegoat/source", "name": "@memegoat/source",
"version": "1.8.0", "version": "1.8.2",
"description": "", "description": "",
"scripts": { "scripts": {
"version:get": "cmake -P version.cmake GET", "version:get": "cmake -P version.cmake GET",