Refactoring

* replace TypeORM with Kysely query builder
* refactor migrations
* other changes and fixes
This commit is contained in:
Philipinho
2024-03-29 01:46:11 +00:00
parent cacb5606b1
commit c18c9ae02b
122 changed files with 2619 additions and 3541 deletions

View File

@ -10,12 +10,11 @@ import { CommentService } from './comment.service';
import { CreateCommentDto } from './dto/create-comment.dto';
import { UpdateCommentDto } from './dto/update-comment.dto';
import { CommentsInput, SingleCommentInput } from './dto/comments.input';
import { ResolveCommentDto } from './dto/resolve-comment.dto';
import { AuthUser } from '../../decorators/auth-user.decorator';
import { User } from '../user/entities/user.entity';
import { AuthWorkspace } from '../../decorators/auth-workspace.decorator';
import { Workspace } from '../workspace/entities/workspace.entity';
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
import { PaginationOptions } from 'src/helpers/pagination/pagination-options';
import { User, Workspace } from '@docmost/db/types/entity.types';
@UseGuards(JwtAuthGuard)
@Controller('comments')
@ -34,8 +33,14 @@ export class CommentController {
@HttpCode(HttpStatus.OK)
@Post()
findPageComments(@Body() input: CommentsInput) {
return this.commentService.findByPageId(input.pageId);
findPageComments(
@Body() input: CommentsInput,
@Body()
pagination: PaginationOptions,
//@AuthUser() user: User,
// @AuthWorkspace() workspace: Workspace,
) {
return this.commentService.findByPageId(input.pageId, pagination);
}
@HttpCode(HttpStatus.OK)
@ -50,15 +55,6 @@ export class CommentController {
return this.commentService.update(updateCommentDto.id, updateCommentDto);
}
@HttpCode(HttpStatus.OK)
@Post('resolve')
resolve(
@Body() resolveCommentDto: ResolveCommentDto,
@AuthUser() user: User,
) {
return this.commentService.resolveComment(user.id, resolveCommentDto);
}
@HttpCode(HttpStatus.OK)
@Post('delete')
remove(@Body() input: SingleCommentInput) {

View File

@ -1,15 +1,12 @@
import { Module } from '@nestjs/common';
import { CommentService } from './comment.service';
import { CommentController } from './comment.controller';
import { CommentRepository } from './repositories/comment.repository';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Comment } from './entities/comment.entity';
import { PageModule } from '../page/page.module';
@Module({
imports: [TypeOrmModule.forFeature([Comment]), PageModule],
imports: [PageModule],
controllers: [CommentController],
providers: [CommentService, CommentRepository],
exports: [CommentService, CommentRepository],
providers: [CommentService],
exports: [CommentService],
})
export class CommentModule {}

View File

@ -1,24 +1,22 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { CreateCommentDto } from './dto/create-comment.dto';
import { UpdateCommentDto } from './dto/update-comment.dto';
import { plainToInstance } from 'class-transformer';
import { Comment } from './entities/comment.entity';
import { CommentRepository } from './repositories/comment.repository';
import { ResolveCommentDto } from './dto/resolve-comment.dto';
import { PageService } from '../page/services/page.service';
import { CommentRepo } from '@docmost/db/repos/comment/comment.repo';
import { Comment } from '@docmost/db/types/entity.types';
import { PaginationOptions } from 'src/helpers/pagination/pagination-options';
import { PaginatedResult } from 'src/helpers/pagination/paginated-result';
import { PaginationMetaDto } from 'src/helpers/pagination/pagination-meta-dto';
@Injectable()
export class CommentService {
constructor(
private commentRepository: CommentRepository,
private commentRepo: CommentRepo,
private pageService: PageService,
) {}
async findWithCreator(commentId: string) {
return await this.commentRepository.findOne({
where: { id: commentId },
relations: ['creator'],
});
// todo: find comment with creator object
}
async create(
@ -26,25 +24,19 @@ export class CommentService {
workspaceId: string,
createCommentDto: CreateCommentDto,
) {
const comment = plainToInstance(Comment, createCommentDto);
comment.creatorId = userId;
comment.workspaceId = workspaceId;
comment.content = JSON.parse(createCommentDto.content);
const commentContent = JSON.parse(createCommentDto.content);
if (createCommentDto.selection) {
comment.selection = createCommentDto.selection.substring(0, 250);
}
const page = await this.pageService.findById(createCommentDto.pageId);
// const spaceId = null; // todo, get from page
const page = await this.pageService.findWithBasic(createCommentDto.pageId);
if (!page) {
throw new BadRequestException('Page not found');
}
if (createCommentDto.parentCommentId) {
const parentComment = await this.commentRepository.findOne({
where: { id: createCommentDto.parentCommentId },
select: ['id', 'parentCommentId'],
});
const parentComment = await this.commentRepo.findById(
createCommentDto.parentCommentId,
);
if (!parentComment) {
throw new BadRequestException('Parent comment not found');
@ -55,68 +47,51 @@ export class CommentService {
}
}
const savedComment = await this.commentRepository.save(comment);
return this.findWithCreator(savedComment.id);
const createdComment = await this.commentRepo.insertComment({
pageId: createCommentDto.pageId,
content: commentContent,
selection: createCommentDto?.selection.substring(0, 250),
type: 'inline', // for now
parentCommentId: createCommentDto?.parentCommentId,
creatorId: userId,
workspaceId: workspaceId,
});
// todo return created comment and creator relation
return createdComment;
}
async findByPageId(pageId: string, offset = 0, limit = 100) {
const comments = this.commentRepository.find({
where: {
pageId: pageId,
},
order: {
createdAt: 'asc',
},
take: limit,
skip: offset,
relations: ['creator'],
});
return comments;
async findByPageId(
pageId: string,
paginationOptions: PaginationOptions,
): Promise<PaginatedResult<Comment>> {
const { comments, count } = await this.commentRepo.findPageComments(
pageId,
paginationOptions,
);
const paginationMeta = new PaginationMetaDto({ count, paginationOptions });
return new PaginatedResult(comments, paginationMeta);
}
async update(
commentId: string,
updateCommentDto: UpdateCommentDto,
): Promise<Comment> {
updateCommentDto.content = JSON.parse(updateCommentDto.content);
const commentContent = JSON.parse(updateCommentDto.content);
const result = await this.commentRepository.update(commentId, {
...updateCommentDto,
editedAt: new Date(),
});
if (result.affected === 0) {
throw new BadRequestException(`Comment not found`);
}
return this.findWithCreator(commentId);
}
async resolveComment(
userId: string,
resolveCommentDto: ResolveCommentDto,
): Promise<Comment> {
const resolvedAt = resolveCommentDto.resolved ? new Date() : null;
const resolvedById = resolveCommentDto.resolved ? userId : null;
const result = await this.commentRepository.update(
resolveCommentDto.commentId,
await this.commentRepo.updateComment(
{
resolvedAt,
resolvedById,
content: commentContent,
editedAt: new Date(),
},
commentId,
);
if (result.affected === 0) {
throw new BadRequestException(`Comment not found`);
}
return this.findWithCreator(resolveCommentDto.commentId);
return this.commentRepo.findById(commentId);
}
async remove(id: string): Promise<void> {
const result = await this.commentRepository.delete(id);
if (result.affected === 0) {
throw new BadRequestException(`Comment with ID ${id} not found.`);
}
await this.commentRepo.deleteComment(id);
}
}

View File

@ -1,9 +0,0 @@
import { IsBoolean, IsUUID } from 'class-validator';
export class ResolveCommentDto {
@IsUUID()
commentId: string;
@IsBoolean()
resolved: boolean;
}

View File

@ -1,82 +0,0 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
CreateDateColumn,
OneToMany,
DeleteDateColumn,
} from 'typeorm';
import { User } from '../../user/entities/user.entity';
import { Page } from '../../page/entities/page.entity';
import { Workspace } from '../../workspace/entities/workspace.entity';
@Entity('comments')
export class Comment {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'jsonb', nullable: true })
content: any;
@Column({ type: 'varchar', length: 255, nullable: true })
selection: string;
@Column({ type: 'varchar', length: 55, nullable: true })
type: string;
@Column()
creatorId: string;
@ManyToOne(() => User, (user) => user.comments)
@JoinColumn({ name: 'creatorId' })
creator: User;
@Column()
pageId: string;
@ManyToOne(() => Page, (page) => page.comments, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'pageId' })
page: Page;
@Column({ type: 'uuid', nullable: true })
parentCommentId: string;
@ManyToOne(() => Comment, (comment) => comment.replies, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'parentCommentId' })
parentComment: Comment;
@OneToMany(() => Comment, (comment) => comment.parentComment)
replies: Comment[];
@Column({ nullable: true })
resolvedById: string;
@ManyToOne(() => User)
@JoinColumn({ name: 'resolvedById' })
resolvedBy: User;
@Column({ type: 'timestamp', nullable: true })
resolvedAt: Date;
@Column()
workspaceId: string;
@ManyToOne(() => Workspace, (workspace) => workspace.comments, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'workspaceId' })
workspace: Workspace;
@CreateDateColumn()
createdAt: Date;
@Column({ type: 'timestamp', nullable: true })
editedAt: Date;
@DeleteDateColumn({ nullable: true })
deletedAt: Date;
}

View File

@ -1,14 +0,0 @@
import { DataSource, Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { Comment } from '../entities/comment.entity';
@Injectable()
export class CommentRepository extends Repository<Comment> {
constructor(private dataSource: DataSource) {
super(Comment, dataSource.createEntityManager());
}
async findById(commentId: string) {
return this.findOneBy({ id: commentId });
}
}