📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
(feature) Extension marketplace comments & replies (#163)
Maksim Mrug491a0d924fe9
diff --git a/apps/production/src/marketplace/comments/comments.controller.spec.ts b/apps/production/src/marketplace/comments/comments.controller.spec.tsdeleted file mode 100644index cf7a3d430..000000000--- a/apps/production/src/marketplace/comments/comments.controller.spec.ts+++ /dev/null@@ -1,18 +0,0 @@-import { Test, TestingModule } from '@nestjs/testing'-import { CommentsController } from './comments.controller'--describe('CommentsController', () => {- let controller: CommentsController-- beforeEach(async () => {- const module: TestingModule = await Test.createTestingModule({- controllers: [CommentsController],- }).compile()-- controller = module.get<CommentsController>(CommentsController)- })-- it('should be defined', () => {- expect(controller).toBeDefined()- })-})diff --git a/apps/production/src/marketplace/comments/comments.controller.ts b/apps/production/src/marketplace/comments/comments.controller.tsindex a2cda928b..f788d9c79 100644--- a/apps/production/src/marketplace/comments/comments.controller.ts+++ b/apps/production/src/marketplace/comments/comments.controller.ts@@ -1,23 +1,36 @@import {Body,Controller,+ ConflictException,Delete,Get,NotFoundException,Param,Post,Query,+ Put,+ BadRequestException,} from '@nestjs/common'import { ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'+import * as _includes from 'lodash/includes'+import * as _omit from 'lodash/omit'import { UserService } from '../../user/user.service'import { ExtensionsService } from '../extensions/extensions.service'+import { Auth, CurrentUserId } from '../../auth/decorators'+import { UserType } from '../../user/entities/user.entity'import { CommentsService } from './comments.service'import { CreateCommentBodyDto } from './dtos/bodies/create-comment.dto'import { DeleteCommentParamDto } from './dtos/params/delete-comment.dto'-import { GetCommentParamDto } from './dtos/params/get-comment.dto'-import { CreateCommentQueryDto } from './dtos/queries/create-comment.dto'import { GetCommentsQueryDto } from './dtos/queries/get-comments.dto'import { Comment } from './entities/comment.entity'+import { CommentReply } from './entities/comment-reply.entity'+import { CreateReplyCommentBodyDto } from './dtos/bodies/create-reply.dto'+import { UpdateCommentReplyBodyDto } from './dtos/bodies/update-reply.dto'++interface IGetComments {+ comments: Comment[]+ count: number+}@ApiTags('comments')@Controller('comments')@@ -28,87 +41,196 @@ export class CommentsController {private readonly userService: UserService,) {}+ @Auth([], true, true)@Get()@ApiQuery({ name: 'offset', required: false, type: String })@ApiQuery({ name: 'limit', required: false, type: String })@ApiQuery({ name: 'extensionId', required: false, type: String })- @ApiQuery({ name: 'userId', required: false, type: String })- async getComments(@Query() queries: GetCommentsQueryDto): Promise<{- comments: Comment[]- count: number- }> {- const [comments, count] = await this.commentsService.findAndCount({- where: {- ...(queries.extensionId && { extensionId: queries.extensionId }),- ...(queries.userId && { userId: queries.userId }),- },- skip: queries.offset || 0,- take: queries.limit || 25,- })-- return { comments, count }- }-- @Get(':commentId')- @ApiParam({ name: 'commentId', required: true, type: String })- async getComment(@Param() params: GetCommentParamDto): Promise<Comment> {- const comment = await this.commentsService.findOne({- where: { id: params.commentId },- })-- if (!comment) {- throw new NotFoundException('Comment not found.')+ async getComments(+ @Query() queries: GetCommentsQueryDto,+ ): Promise<IGetComments> {+ const [comments, count] = await this.commentsService.getCommentsByExtId(+ queries.extensionId,+ Number(queries.offset) || 0,+ Number(queries.limit) || 25,+ )++ return {+ comments,+ count,}-- return comment}+ @Auth([UserType.CUSTOMER, UserType.ADMIN])@Post()@ApiQuery({ name: 'userId', required: true, type: String })async createComment(- @Query() queries: CreateCommentQueryDto,@Body() body: CreateCommentBodyDto,+ @CurrentUserId() userId: string,): Promise<Comment> {+ const user = await this.userService.findOne(userId)++ if (!user) {+ throw new NotFoundException('User not found.')+ }++ if (!user.nickname) {+ throw new BadRequestException('You must have a nickname to comment.')+ }+const extension = await this.extensionsService.findOne({where: { id: body.extensionId },+ relations: ['owner'],})- if (!extension) {+ if (!extension || !extension.owner) {throw new NotFoundException('Extension not found.')}- const user = await this.userService.findOne(queries.userId)-- if (!user) {- throw new NotFoundException('User not found.')+ if (extension.owner.id === userId) {+ throw new ConflictException('You cannot comment on your own extension.')}const comment = await this.commentsService.findOne({- where: { extensionId: body.extensionId, userId: queries.userId },+ where: { extensionId: body.extensionId, userId },})if (comment) {- throw new NotFoundException('Comment already exists.')+ throw new BadRequestException(+ 'You have already commented on this extension.',+ )}return this.commentsService.save({...body,- extensionId: Number(body.extensionId),- userId: Number(queries.userId),+ extensionId: extension.id,+ userId,})}+ @Auth([UserType.CUSTOMER, UserType.ADMIN])@Delete(':commentId')@ApiParam({ name: 'commentId', required: true, type: String })- async deleteComment(@Param() params: DeleteCommentParamDto): Promise<void> {+ async deleteComment(+ @Param() params: DeleteCommentParamDto,+ @CurrentUserId() userId: string,+ ): Promise<void> {const comment = await this.commentsService.findOne({where: { id: params.commentId },+ relations: ['user', 'extension', 'extension.owner'],})if (!comment) {throw new NotFoundException('Comment not found.')}+ const user = await this.userService.findOne(userId)++ if (!_includes(user.roles, UserType.ADMIN) && comment.user.id !== userId) {+ throw new ConflictException('You are not allowed to do this.')+ }+await this.commentsService.delete(params.commentId)}++ @Auth([UserType.ADMIN, UserType.CUSTOMER])+ @Post('reply')+ async createCommentReply(+ @Body() commentReplyDto: CreateReplyCommentBodyDto,+ @CurrentUserId() userId: string,+ ): Promise<CommentReply & { isOwner?: boolean }> {+ const user = await this.userService.findOne(userId)++ if (!user) {+ throw new NotFoundException('User not found.')+ }++ if (!user.nickname) {+ throw new BadRequestException('You must have a nickname to reply.')+ }++ const comment = await this.commentsService.findOne({+ where: { id: commentReplyDto.commentId },+ })++ if (!comment) {+ throw new NotFoundException('Comment not found')+ }++ const hasUserReplied = await this.commentsService.haveUserRepliedToComment(+ comment.id,+ userId,+ )++ if (hasUserReplied) {+ throw new BadRequestException('You have already replied to this comment')+ }++ const replyComment = await this.commentsService.createCommentReply(+ commentReplyDto,+ comment,+ userId,+ )++ return {+ ...replyComment,+ parentComment: _omit(replyComment.parentComment, ['userId']),+ isOwner: true,+ }+ }++ @Auth([UserType.ADMIN, UserType.CUSTOMER])+ @Put('reply/:id')+ async updateCommentReply(+ @Param('id') id: string,+ @Body() commentReplyDto: UpdateCommentReplyBodyDto,+ @CurrentUserId() userId: string,+ ): Promise<CommentReply & { isOwner: boolean }> {+ const commentReply = await this.commentsService.findCommentReplyById(id)++ if (!commentReply) {+ throw new NotFoundException('Comment reply not found')+ }++ if (commentReply.user.id !== userId) {+ throw new BadRequestException(+ 'You are not the owner of this comment reply',+ )+ }++ const updatedReplyComment = await this.commentsService.updateCommentReply(+ id,+ commentReplyDto,+ )++ return {+ ...updatedReplyComment,+ isOwner: updatedReplyComment.user.id === userId,+ }+ }++ @Auth([UserType.ADMIN, UserType.CUSTOMER])+ @Delete('reply/:id')+ async deleteCommentReply(+ @Param('id') id: string,+ @CurrentUserId() userId: string,+ ): Promise<void> {+ const commentReply = await this.commentsService.findCommentReplyById(id)++ if (!commentReply) {+ throw new NotFoundException('Comment reply not found.')+ }++ const user = await this.userService.findOne(userId)++ if (+ !(+ commentReply.user.id === userId || _includes(user.roles, UserType.ADMIN)+ )+ ) {+ throw new ConflictException('You are not allowed to do this.')+ }++ await this.commentsService.deleteCommentReply(id)+ }}diff --git a/apps/production/src/marketplace/comments/comments.module.ts b/apps/production/src/marketplace/comments/comments.module.tsindex 21ac9eb91..f4371c595 100644--- a/apps/production/src/marketplace/comments/comments.module.ts+++ b/apps/production/src/marketplace/comments/comments.module.ts@@ -5,9 +5,14 @@ import { ExtensionsModule } from '../extensions/extensions.module'import { CommentsController } from './comments.controller'import { CommentsService } from './comments.service'import { Comment } from './entities/comment.entity'+import { CommentReply } from './entities/comment-reply.entity'@Module({- imports: [TypeOrmModule.forFeature([Comment]), ExtensionsModule, UserModule],+ imports: [+ TypeOrmModule.forFeature([Comment, CommentReply]),+ ExtensionsModule,+ UserModule,+ ],controllers: [CommentsController],providers: [CommentsService],})diff --git a/apps/production/src/marketplace/comments/comments.service.spec.ts b/apps/production/src/marketplace/comments/comments.service.spec.tsdeleted file mode 100644index 409d6f13d..000000000--- a/apps/production/src/marketplace/comments/comments.service.spec.ts+++ /dev/null@@ -1,18 +0,0 @@-import { Test, TestingModule } from '@nestjs/testing'-import { CommentsService } from './comments.service'--describe('CommentsService', () => {- let service: CommentsService-- beforeEach(async () => {- const module: TestingModule = await Test.createTestingModule({- providers: [CommentsService],- }).compile()-- service = module.get<CommentsService>(CommentsService)- })-- it('should be defined', () => {- expect(service).toBeDefined()- })-})diff --git a/apps/production/src/marketplace/comments/comments.service.ts b/apps/production/src/marketplace/comments/comments.service.tsindex 8c89b1858..1b7a817f2 100644--- a/apps/production/src/marketplace/comments/comments.service.ts+++ b/apps/production/src/marketplace/comments/comments.service.ts@@ -1,12 +1,19 @@import { Injectable } from '@nestjs/common'import { InjectRepository } from '@nestjs/typeorm'import { FindManyOptions, FindOneOptions, Repository } from 'typeorm'+import * as _isEmpty from 'lodash/isEmpty'import { Comment } from './entities/comment.entity'+import { CreateReplyCommentBodyDto } from './dtos/bodies/create-reply.dto'+import { UpdateCommentReplyBodyDto } from './dtos/bodies/update-reply.dto'+import { CommentReply } from './entities/comment-reply.entity'@Injectable()export class CommentsService {constructor(- @InjectRepository(Comment) private commentsRepository: Repository<Comment>,+ @InjectRepository(Comment)+ private commentsRepository: Repository<Comment>,+ @InjectRepository(CommentReply)+ private commentReplyRepository: Repository<CommentReply>,) {}async findAndCount(@@ -15,17 +22,102 @@ export class CommentsService {return this.commentsRepository.findAndCount({ ...options })}+ async getCommentsByExtId(extensionId: string, skip: number, take: number) {+ return this.commentsRepository+ .createQueryBuilder('comment')+ .where('comment.extensionId = :extensionId', { extensionId })+ .leftJoinAndSelect('comment.replies', 'reply')+ .leftJoinAndSelect('reply.user', 'replyUser')+ .leftJoinAndSelect('comment.user', 'commentUser')+ .select([+ 'comment.id',+ 'comment.text',+ 'comment.addedAt',+ 'comment.extensionId',+ 'comment.rating',+ // 'commentUser.id',+ 'commentUser.nickname',+ 'reply.id',+ 'reply.text',+ 'reply.addedAt',+ 'replyUser.nickname',+ ])+ .skip(skip)+ .take(take)+ .getManyAndCount()+ }+async findOne(options: FindOneOptions<Comment>): Promise<Comment> {return this.commentsRepository.findOne({ ...options })}- async save(- comment: Omit<Comment, 'id' | 'addedAt' | 'extension' | 'user'>,- ): Promise<Comment> {+ async save(comment: Partial<Comment>): Promise<Comment> {return this.commentsRepository.save(comment)}async delete(id: string): Promise<void> {await this.commentsRepository.delete(id)}++ async update(id: string, comment: Partial<Comment>): Promise<Comment> {+ await this.commentsRepository.update(id, comment)+ return this.commentsRepository.findOne(id)+ }++ async createCommentReply(+ commentReplyDto: CreateReplyCommentBodyDto,+ comment: Comment,+ userId: string,+ ): Promise<CommentReply> {+ const commentReply = this.commentReplyRepository.create({+ text: commentReplyDto.text,+ parentComment: comment,+ userId,+ })+ return this.commentReplyRepository.save(commentReply)+ }++ async haveUserRepliedToComment(+ commentId: string,+ userId: string,+ ): Promise<boolean> {+ return !_isEmpty(+ await this.commentReplyRepository+ .createQueryBuilder('reply')+ .where('reply.parentCommentId = :id', { id: commentId })+ .andWhere('reply.userId = :userId', { userId })+ // .leftJoinAndSelect('reply.parentComment', 'parentComment')+ // .leftJoinAndSelect('reply.user', 'user')+ .select(['reply.id'])+ .getOne(),+ )+ }++ async findCommentReplyById(id: string) {+ return this.commentReplyRepository+ .createQueryBuilder('reply')+ .where('reply.id = :id', { id })+ .leftJoinAndSelect('reply.user', 'user')+ .select([+ 'reply.id',+ 'reply.text',+ 'reply.addedAt',+ 'user.nickname',+ 'user.id',+ ])+ .getOne()+ }++ async updateCommentReply(+ id: string,+ commentReplyDto: UpdateCommentReplyBodyDto,+ ): Promise<CommentReply | undefined> {+ await this.commentReplyRepository.update(id, commentReplyDto)++ return this.findCommentReplyById(id)+ }++ async deleteCommentReply(id: string): Promise<void> {+ await this.commentReplyRepository.delete(id)+ }}diff --git a/apps/production/src/marketplace/comments/dtos/bodies/create-comment.dto.ts b/apps/production/src/marketplace/comments/dtos/bodies/create-comment.dto.tsindex db7f699c3..fa4ff90d3 100644--- a/apps/production/src/marketplace/comments/dtos/bodies/create-comment.dto.ts+++ b/apps/production/src/marketplace/comments/dtos/bodies/create-comment.dto.ts@@ -1,10 +1,10 @@import { ApiProperty } from '@nestjs/swagger'-import { IsNumber, IsString, Max, Min } from 'class-validator'+import { IsNumber, IsString, IsUUID, Max, Min } from 'class-validator'export class CreateCommentBodyDto {@ApiProperty()- @IsNumber()- extensionId: number+ @IsUUID()+ extensionId: string@ApiProperty()@IsString()diff --git a/apps/production/src/marketplace/comments/dtos/bodies/create-reply.dto.ts b/apps/production/src/marketplace/comments/dtos/bodies/create-reply.dto.tsnew file mode 100644index 000000000..6832be80d--- /dev/null+++ b/apps/production/src/marketplace/comments/dtos/bodies/create-reply.dto.ts@@ -0,0 +1,14 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty, IsString, IsUUID } from 'class-validator'++export class CreateReplyCommentBodyDto {+ @ApiProperty()+ @IsUUID()+ @IsNotEmpty()+ commentId: string++ @ApiProperty()+ @IsString()+ @IsNotEmpty()+ text: string | null+}diff --git a/apps/production/src/marketplace/comments/dtos/bodies/update-reply.dto.ts b/apps/production/src/marketplace/comments/dtos/bodies/update-reply.dto.tsnew file mode 100644index 000000000..40895e9be--- /dev/null+++ b/apps/production/src/marketplace/comments/dtos/bodies/update-reply.dto.ts@@ -0,0 +1,9 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty, IsString } from 'class-validator'++export class UpdateCommentReplyBodyDto {+ @ApiProperty()+ @IsString()+ @IsNotEmpty()+ text: string | null+}diff --git a/apps/production/src/marketplace/comments/dtos/params/delete-comment.dto.ts b/apps/production/src/marketplace/comments/dtos/params/delete-comment.dto.tsindex aa60f5529..f74dad185 100644--- a/apps/production/src/marketplace/comments/dtos/params/delete-comment.dto.ts+++ b/apps/production/src/marketplace/comments/dtos/params/delete-comment.dto.ts@@ -1,6 +1,6 @@-import { IsNumberString } from 'class-validator'+import { IsUUID } from 'class-validator'export class DeleteCommentParamDto {- @IsNumberString()+ @IsUUID()commentId: string}diff --git a/apps/production/src/marketplace/comments/dtos/params/get-comment.dto.ts b/apps/production/src/marketplace/comments/dtos/params/get-comment.dto.tsindex ebf2335b2..65446be80 100644--- a/apps/production/src/marketplace/comments/dtos/params/get-comment.dto.ts+++ b/apps/production/src/marketplace/comments/dtos/params/get-comment.dto.ts@@ -1,6 +1,6 @@-import { IsNumberString } from 'class-validator'+import { IsUUID } from 'class-validator'export class GetCommentParamDto {- @IsNumberString()+ @IsUUID()commentId: string}diff --git a/apps/production/src/marketplace/comments/dtos/queries/create-comment.dto.ts b/apps/production/src/marketplace/comments/dtos/queries/create-comment.dto.tsindex 74f460f78..0ebe3680e 100644--- a/apps/production/src/marketplace/comments/dtos/queries/create-comment.dto.ts+++ b/apps/production/src/marketplace/comments/dtos/queries/create-comment.dto.ts@@ -1,8 +1,8 @@import { ApiProperty } from '@nestjs/swagger'-import { IsNumberString } from 'class-validator'+import { IsUUID } from 'class-validator'export class CreateCommentQueryDto {@ApiProperty()- @IsNumberString()+ @IsUUID()userId: string}diff --git a/apps/production/src/marketplace/comments/dtos/queries/get-comments.dto.ts b/apps/production/src/marketplace/comments/dtos/queries/get-comments.dto.tsindex 0ac8ea272..da12fc364 100644--- a/apps/production/src/marketplace/comments/dtos/queries/get-comments.dto.ts+++ b/apps/production/src/marketplace/comments/dtos/queries/get-comments.dto.ts@@ -1,4 +1,4 @@-import { IsNumberString, IsOptional } from 'class-validator'+import { IsNumberString, IsOptional, IsString, IsUUID } from 'class-validator'export class GetCommentsQueryDto {@IsNumberString()@@ -9,11 +9,11 @@ export class GetCommentsQueryDto {@IsOptional()limit?: number- @IsNumberString()- @IsOptional()- extensionId?: number+ @IsString()+ extensionId: string- @IsNumberString()+ @IsString()@IsOptional()- userId?: number+ @IsUUID()+ userId?: string}diff --git a/apps/production/src/marketplace/comments/entities/comment-reply.entity.ts b/apps/production/src/marketplace/comments/entities/comment-reply.entity.tsnew file mode 100644index 000000000..8b882f190--- /dev/null+++ b/apps/production/src/marketplace/comments/entities/comment-reply.entity.ts@@ -0,0 +1,32 @@+import {+ Column,+ CreateDateColumn,+ Entity,+ ManyToOne,+ PrimaryGeneratedColumn,+ JoinColumn,+} from 'typeorm'+import { Comment } from './comment.entity'+import { User } from '../../../user/entities/user.entity'++@Entity()+export class CommentReply {+ @PrimaryGeneratedColumn('uuid')+ id: string++ @ManyToOne(() => Comment, comment => comment.replies, { onDelete: 'CASCADE' })+ parentComment: Comment++ @Column()+ userId: string++ @Column('text')+ text: string++ @CreateDateColumn()+ addedAt: Date++ @ManyToOne(() => User, user => user.commentReplies, { onDelete: 'CASCADE' })+ @JoinColumn()+ user: User+}diff --git a/apps/production/src/marketplace/comments/entities/comment.entity.ts b/apps/production/src/marketplace/comments/entities/comment.entity.tsindex 91f1f8637..4cdd357bf 100644--- a/apps/production/src/marketplace/comments/entities/comment.entity.ts+++ b/apps/production/src/marketplace/comments/entities/comment.entity.ts@@ -4,21 +4,23 @@ import {Entity,JoinColumn,ManyToOne,+ OneToMany,PrimaryGeneratedColumn,} from 'typeorm'import { Extension } from '../../extensions/entities/extension.entity'import { User } from '../../../user/entities/user.entity'+import { CommentReply } from './comment-reply.entity'@Entity()export class Comment {- @PrimaryGeneratedColumn()- id: number+ @PrimaryGeneratedColumn('uuid')+ id: string@Column()- extensionId: number+ extensionId: string@Column()- userId: number+ userId: string@Column('text', { nullable: true, default: null })text: string | null@@ -38,4 +40,7 @@ export class Comment {@ManyToOne(() => User, user => user.comments, { onDelete: 'CASCADE' })@JoinColumn()user: User++ @OneToMany(() => CommentReply, reply => reply.parentComment)+ replies: CommentReply[]}diff --git a/apps/production/src/user/entities/user.entity.ts b/apps/production/src/user/entities/user.entity.tsindex 7c4895314..0db5917eb 100644--- a/apps/production/src/user/entities/user.entity.ts+++ b/apps/production/src/user/entities/user.entity.ts@@ -13,6 +13,7 @@ import { Extension } from '../../marketplace/extensions/entities/extension.entitimport { ExtensionToUser } from '../../marketplace/extensions/entities/extension-to-user.entity'import { Payout } from '../../payouts/entities/payouts.entity'import { Comment } from '../../marketplace/comments/entities/comment.entity'+import { CommentReply } from '../../marketplace/comments/entities/comment-reply.entity'import { Complaint } from '../../marketplace/complaints/entities/complaint.entity'import { RefreshToken } from './refresh-token.entity'@@ -360,6 +361,10 @@ export class User {@JoinTable()comments: Comment[]+ @OneToMany(() => CommentReply, comment => comment.user)+ @JoinTable()+ commentReplies: CommentReply[]+@OneToMany(() => Complaint, complaint => complaint.user)@JoinTable()complaints: Complaint[]diff --git a/migrations/mysql/2023_10_21.sql b/migrations/mysql/2023_10_21.sqlnew file mode 100644index 000000000..080f32dc0--- /dev/null+++ b/migrations/mysql/2023_10_21.sql@@ -0,0 +1,22 @@+CREATE TABLE `comment` (+ `extensionId` varchar(255) NOT NULL,+ `userId` varchar(255) NOT NULL,+ `text` text,+ `rating` int DEFAULT NULL,+ `addedAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),+ `id` varchar(36) NOT NULL,+ PRIMARY KEY (`id`),+ FOREIGN KEY (`extensionId`) REFERENCES `extension` (`id`) ON DELETE CASCADE,+ FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;++CREATE TABLE `comment_reply` (+ `id` varchar(36) NOT NULL,+ `userId` varchar(255) NOT NULL,+ `text` text NOT NULL,+ `addedAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),+ `parentCommentId` varchar(36) DEFAULT NULL,+ PRIMARY KEY (`id`),+ FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE,+ FOREIGN KEY (`parentCommentId`) REFERENCES `comment` (`id`) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;