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

@ -3,7 +3,7 @@ import { IsOptional, IsString, IsUUID } from 'class-validator';
export class CreatePageDto {
@IsOptional()
@IsUUID()
id?: string;
pageId?: string;
@IsOptional()
@IsString()

View File

@ -2,5 +2,5 @@ import { IsUUID } from 'class-validator';
export class DeletePageDto {
@IsUUID()
id: string;
pageId: string;
}

View File

@ -2,5 +2,5 @@ import { IsUUID } from 'class-validator';
export class HistoryDetailsDto {
@IsUUID()
id: string;
historyId: string;
}

View File

@ -2,7 +2,7 @@ import { IsString, IsOptional, IsUUID } from 'class-validator';
export class MovePageDto {
@IsUUID()
id: string;
pageId: string;
@IsOptional()
@IsString()

View File

@ -2,5 +2,5 @@ import { IsUUID } from 'class-validator';
export class PageDetailsDto {
@IsUUID()
id: string;
pageId: string;
}

View File

@ -1,5 +1,3 @@
import { Page } from '../entities/page.entity';
import { Page } from '@docmost/db/types/entity.types';
export class PageWithOrderingDto extends Page {
childrenIds?: string[];
}
export type PageWithOrderingDto = Page & { childrenIds?: string[] };

View File

@ -4,5 +4,5 @@ import { IsUUID } from 'class-validator';
export class UpdatePageDto extends PartialType(CreatePageDto) {
@IsUUID()
id: string;
pageId: string;
}

View File

@ -1,71 +0,0 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';
import { Workspace } from '../../workspace/entities/workspace.entity';
import { Page } from './page.entity';
import { User } from '../../user/entities/user.entity';
import { Space } from '../../space/entities/space.entity';
@Entity('page_history')
export class PageHistory {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid' })
pageId: string;
@ManyToOne(() => Page, (page) => page.pageHistory, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'pageId' })
page: Page;
@Column({ length: 500, nullable: true })
title: string;
@Column({ type: 'jsonb', nullable: true })
content: string;
@Column({ nullable: true })
slug: string;
@Column({ nullable: true })
icon: string;
@Column({ nullable: true })
coverPhoto: string;
@Column({ type: 'int' })
version: number;
@Column({ type: 'uuid' })
lastUpdatedById: string;
@ManyToOne(() => User)
@JoinColumn({ name: 'lastUpdatedById' })
lastUpdatedBy: User;
@Column()
spaceId: string;
@ManyToOne(() => Space, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'spaceId' })
space: Space;
@Column()
workspaceId: string;
@ManyToOne(() => Workspace, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'workspaceId' })
workspace: Workspace;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}

View File

@ -1,56 +0,0 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
Unique,
CreateDateColumn,
UpdateDateColumn,
DeleteDateColumn,
} from 'typeorm';
import { Workspace } from '../../workspace/entities/workspace.entity';
import { Space } from '../../space/entities/space.entity';
@Entity('page_ordering')
@Unique(['entityId', 'entityType'])
export class PageOrdering {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column('uuid')
entityId: string;
@Column({ type: 'varchar', length: 50, nullable: false })
entityType: string;
@Column('uuid', { array: true, default: '{}' })
childrenIds: string[];
@Column('uuid')
workspaceId: string;
@ManyToOne(() => Workspace, (workspace) => workspace.id, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'workspaceId' })
workspace: Workspace;
@Column('uuid')
spaceId: string;
@ManyToOne(() => Space, (space) => space.id, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'spaceId' })
space: Space;
@DeleteDateColumn({ nullable: true })
deletedAt: Date;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}

View File

@ -1,130 +0,0 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
OneToMany,
DeleteDateColumn,
Index,
} from 'typeorm';
import { User } from '../../user/entities/user.entity';
import { Workspace } from '../../workspace/entities/workspace.entity';
import { Comment } from '../../comment/entities/comment.entity';
import { PageHistory } from './page-history.entity';
import { Space } from '../../space/entities/space.entity';
@Entity('pages')
@Index(['tsv'])
export class Page {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ length: 500, nullable: true })
title: string;
@Column({ nullable: true })
icon: string;
@Column({ type: 'jsonb', nullable: true })
content: string;
@Column({ type: 'text', nullable: true })
html: string;
@Column({ type: 'text', nullable: true })
textContent: string;
@Column({
type: 'tsvector',
select: false,
nullable: true,
})
tsv: string;
@Column({ type: 'bytea', nullable: true })
ydoc: any;
@Column({ nullable: true })
slug: string;
@Column({ nullable: true })
coverPhoto: string;
@Column({ length: 255, nullable: true })
editor: string;
@Column({ length: 255, nullable: true })
shareId: string;
@Column({ type: 'uuid', nullable: true })
parentPageId: string;
@Column()
creatorId: string;
@ManyToOne(() => User)
@JoinColumn({ name: 'creatorId' })
creator: User;
@Column({ type: 'uuid', nullable: true })
lastUpdatedById: string;
@ManyToOne(() => User)
@JoinColumn({ name: 'lastUpdatedById' })
lastUpdatedBy: User;
@Column({ type: 'uuid', nullable: true })
deletedById: string;
@ManyToOne(() => User)
@JoinColumn({ name: 'deletedById' })
deletedBy: User;
@Column()
spaceId: string;
@ManyToOne(() => Space, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'spaceId' })
space: Space;
@Column()
workspaceId: string;
@ManyToOne(() => Workspace, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'workspaceId' })
workspace: Workspace;
@Column({ type: 'boolean', default: false })
isLocked: boolean;
@Column({ length: 255, nullable: true })
status: string;
@Column({ type: 'date', nullable: true })
publishedAt: Date;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@DeleteDateColumn({ nullable: true })
deletedAt: Date;
@ManyToOne(() => Page, (page) => page.childPages)
@JoinColumn({ name: 'parentPageId' })
parentPage: Page;
@OneToMany(() => Page, (page) => page.parentPage, { onDelete: 'CASCADE' })
childPages: Page[];
@OneToMany(() => PageHistory, (pageHistory) => pageHistory.page)
pageHistory: PageHistory[];
@OneToMany(() => Comment, (comment) => comment.page)
comments: Comment[];
}

View File

@ -17,10 +17,10 @@ import { PageHistoryService } from './services/page-history.service';
import { HistoryDetailsDto } from './dto/history-details.dto';
import { PageHistoryDto } from './dto/page-history.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('pages')
@ -34,7 +34,7 @@ export class PageController {
@HttpCode(HttpStatus.OK)
@Post('/info')
async getPage(@Body() input: PageDetailsDto) {
return this.pageService.findOne(input.id);
return this.pageService.findById(input.pageId);
}
@HttpCode(HttpStatus.CREATED)
@ -50,19 +50,23 @@ export class PageController {
@HttpCode(HttpStatus.OK)
@Post('update')
async update(@Body() updatePageDto: UpdatePageDto, @AuthUser() user: User) {
return this.pageService.update(updatePageDto.id, updatePageDto, user.id);
return this.pageService.update(
updatePageDto.pageId,
updatePageDto,
user.id,
);
}
@HttpCode(HttpStatus.OK)
@Post('delete')
async delete(@Body() deletePageDto: DeletePageDto) {
await this.pageService.delete(deletePageDto.id);
await this.pageService.forceDelete(deletePageDto.pageId);
}
@HttpCode(HttpStatus.OK)
@Post('restore')
async restore(@Body() deletePageDto: DeletePageDto) {
await this.pageService.restore(deletePageDto.id);
// await this.pageService.restore(deletePageDto.id);
}
@HttpCode(HttpStatus.OK)
@ -73,9 +77,11 @@ export class PageController {
@HttpCode(HttpStatus.OK)
@Post('recent')
async getRecentSpacePages(@Body() { spaceId }) {
console.log(spaceId);
return this.pageService.getRecentSpacePages(spaceId);
async getRecentSpacePages(
@Body() { spaceId },
@Body() pagination: PaginationOptions,
) {
return this.pageService.getRecentSpacePages(spaceId, pagination);
}
@HttpCode(HttpStatus.OK)
@ -96,15 +102,19 @@ export class PageController {
return this.pageOrderService.convertToTree(spaceId);
}
// TODO: scope to workspaces
@HttpCode(HttpStatus.OK)
@Post('/history')
async getPageHistory(@Body() dto: PageHistoryDto) {
return this.pageHistoryService.findHistoryByPageId(dto.pageId);
async getPageHistory(
@Body() dto: PageHistoryDto,
@Body() pagination: PaginationOptions,
) {
return this.pageHistoryService.findHistoryByPageId(dto.pageId, pagination);
}
@HttpCode(HttpStatus.OK)
@Post('/history/details')
async get(@Body() dto: HistoryDetailsDto) {
return this.pageHistoryService.findOne(dto.id);
return this.pageHistoryService.findById(dto.historyId);
}
}

View File

@ -1,34 +1,14 @@
import { Module } from '@nestjs/common';
import { PageService } from './services/page.service';
import { PageController } from './page.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Page } from './entities/page.entity';
import { PageRepository } from './repositories/page.repository';
import { WorkspaceModule } from '../workspace/workspace.module';
import { PageOrderingService } from './services/page-ordering.service';
import { PageOrdering } from './entities/page-ordering.entity';
import { PageHistoryService } from './services/page-history.service';
import { PageHistory } from './entities/page-history.entity';
import { PageHistoryRepository } from './repositories/page-history.repository';
@Module({
imports: [
TypeOrmModule.forFeature([Page, PageOrdering, PageHistory]),
WorkspaceModule,
],
imports: [WorkspaceModule],
controllers: [PageController],
providers: [
PageService,
PageOrderingService,
PageHistoryService,
PageRepository,
PageHistoryRepository,
],
exports: [
PageService,
PageOrderingService,
PageHistoryService,
PageRepository,
],
providers: [PageService, PageOrderingService, PageHistoryService],
exports: [PageService, PageOrderingService, PageHistoryService],
})
export class PageModule {}

View File

@ -1,10 +1,11 @@
import { KyselyTransaction } from '@docmost/db/types/kysely.types';
import { MovePageDto } from './dto/move-page.dto';
import { EntityManager } from 'typeorm';
import { PageOrdering } from '@docmost/db/types/entity.types';
export enum OrderingEntity {
workspace = 'SPACE',
space = 'SPACE',
page = 'PAGE',
WORKSPACE = 'WORKSPACE',
SPACE = 'SPACE',
PAGE = 'PAGE',
}
export type TreeNode = {
@ -15,7 +16,7 @@ export type TreeNode = {
};
export function orderPageList(arr: string[], payload: MovePageDto): void {
const { id, after, before } = payload;
const { pageId: id, after, before } = payload;
// Removing the item we are moving from the array first.
const index = arr.indexOf(id);
@ -46,23 +47,27 @@ export function orderPageList(arr: string[], payload: MovePageDto): void {
}
/**
* Remove an item from an array and save the entity
* @param entity - The entity instance (Page or Workspace)
* Remove an item from an array and update the entity
* @param entity - The entity instance (Page or Space)
* @param arrayField - The name of the field which is an array
* @param itemToRemove - The item to remove from the array
* @param manager - EntityManager instance
*/
export async function removeFromArrayAndSave<T>(
entity: T,
export async function removeFromArrayAndSave(
entity: PageOrdering,
arrayField: string,
itemToRemove: any,
manager: EntityManager,
trx: KyselyTransaction,
) {
const array = entity[arrayField];
const index = array.indexOf(itemToRemove);
if (index > -1) {
array.splice(index, 1);
await manager.save(entity);
await trx
.updateTable('page_ordering')
.set(entity)
.where('id', '=', entity.id)
.execute();
}
}
@ -70,11 +75,11 @@ export function transformPageResult(result: any[]): any[] {
return result.map((row) => {
const processedRow = {};
for (const key in row) {
const newKey = key.split('_').slice(1).join('_');
if (newKey === 'childrenIds' && !row[key]) {
processedRow[newKey] = [];
//const newKey = key.split('_').slice(1).join('_');
if (key === 'childrenIds' && !row[key]) {
processedRow[key] = [];
} else {
processedRow[newKey] = row[key];
processedRow[key] = row[key];
}
}
return processedRow;

View File

@ -1,26 +0,0 @@
import { DataSource, Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { PageHistory } from '../entities/page-history.entity';
@Injectable()
export class PageHistoryRepository extends Repository<PageHistory> {
constructor(private dataSource: DataSource) {
super(PageHistory, dataSource.createEntityManager());
}
async findById(pageId: string) {
return this.findOne({
where: {
id: pageId,
},
relations: ['lastUpdatedBy'],
select: {
lastUpdatedBy: {
id: true,
name: true,
avatarUrl: true,
},
},
});
}
}

View File

@ -1,57 +0,0 @@
import { DataSource, Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { Page } from '../entities/page.entity';
@Injectable()
export class PageRepository extends Repository<Page> {
constructor(private dataSource: DataSource) {
super(Page, dataSource.createEntityManager());
}
public baseFields = [
'page.id',
'page.title',
'page.slug',
'page.icon',
'page.coverPhoto',
'page.shareId',
'page.parentPageId',
'page.creatorId',
'page.lastUpdatedById',
'page.spaceId',
'page.workspaceId',
'page.isLocked',
'page.status',
'page.publishedAt',
'page.createdAt',
'page.updatedAt',
'page.deletedAt',
];
private async baseFind(pageId: string, selectFields: string[]) {
return this.dataSource
.createQueryBuilder(Page, 'page')
.where('page.id = :id', { id: pageId })
.select(selectFields)
.getOne();
}
async findById(pageId: string) {
return this.baseFind(pageId, this.baseFields);
}
async findWithYDoc(pageId: string) {
const extendedFields = [...this.baseFields, 'page.ydoc'];
return this.baseFind(pageId, extendedFields);
}
async findWithContent(pageId: string) {
const extendedFields = [...this.baseFields, 'page.content'];
return this.baseFind(pageId, extendedFields);
}
async findWithAllFields(pageId: string) {
const extendedFields = [...this.baseFields, 'page.content', 'page.ydoc'];
return this.baseFind(pageId, extendedFields);
}
}

View File

@ -1,13 +1,15 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { PageHistory } from '../entities/page-history.entity';
import { Page } from '../entities/page.entity';
import { PageHistoryRepository } from '../repositories/page-history.repository';
import { PageHistoryRepo } from '@docmost/db/repos/page/page-history.repo';
import { Page, PageHistory } 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 PageHistoryService {
constructor(private pageHistoryRepo: PageHistoryRepository) {}
constructor(private pageHistoryRepo: PageHistoryRepo) {}
async findOne(historyId: string): Promise<PageHistory> {
async findById(historyId: string): Promise<PageHistory> {
const history = await this.pageHistoryRepo.findById(historyId);
if (!history) {
throw new BadRequestException('History not found');
@ -16,45 +18,31 @@ export class PageHistoryService {
}
async saveHistory(page: Page): Promise<void> {
const pageHistory = new PageHistory();
pageHistory.pageId = page.id;
pageHistory.title = page.title;
pageHistory.content = page.content;
pageHistory.slug = page.slug;
pageHistory.icon = page.icon;
pageHistory.version = 1; // TODO: make incremental
pageHistory.coverPhoto = page.coverPhoto;
pageHistory.lastUpdatedById = page.lastUpdatedById ?? page.creatorId;
pageHistory.workspaceId = page.workspaceId;
await this.pageHistoryRepo.save(pageHistory);
await this.pageHistoryRepo.insertPageHistory({
pageId: page.id,
title: page.title,
content: page.content,
slug: page.slug,
icon: page.icon,
version: 1, // TODO: make incremental
coverPhoto: page.coverPhoto,
lastUpdatedById: page.lastUpdatedById ?? page.creatorId,
spaceId: page.spaceId,
workspaceId: page.workspaceId,
});
}
async findHistoryByPageId(pageId: string, limit = 50, offset = 0) {
const history = await this.pageHistoryRepo
.createQueryBuilder('history')
.where('history.pageId = :pageId', { pageId })
.leftJoinAndSelect('history.lastUpdatedBy', 'user')
.select([
'history.id',
'history.pageId',
'history.title',
'history.slug',
'history.icon',
'history.coverPhoto',
'history.version',
'history.lastUpdatedById',
'history.workspaceId',
'history.createdAt',
'history.updatedAt',
'user.id',
'user.name',
'user.avatarUrl',
])
.orderBy('history.updatedAt', 'DESC')
.offset(offset)
.take(limit)
.getMany();
return history;
async findHistoryByPageId(
pageId: string,
paginationOptions: PaginationOptions,
) {
const { pageHistory, count } =
await this.pageHistoryRepo.findPageHistoryByPageId(
pageId,
paginationOptions,
);
const paginationMeta = new PaginationMetaDto({ count, paginationOptions });
return new PaginatedResult(pageHistory, paginationMeta);
}
}

View File

@ -1,11 +1,9 @@
import {
BadRequestException,
forwardRef,
Inject,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { PageRepository } from '../repositories/page.repository';
import { Page } from '../entities/page.entity';
import { MovePageDto } from '../dto/move-page.dto';
import {
OrderingEntity,
@ -13,141 +11,185 @@ import {
removeFromArrayAndSave,
TreeNode,
} from '../page.util';
import { DataSource, EntityManager } from 'typeorm';
import { PageService } from './page.service';
import { PageOrdering } from '../entities/page-ordering.entity';
import { InjectKysely } from 'nestjs-kysely';
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
import { executeTx } from '@docmost/db/utils';
import { Page, PageOrdering } from '@docmost/db/types/entity.types';
import { PageWithOrderingDto } from '../dto/page-with-ordering.dto';
@Injectable()
export class PageOrderingService {
constructor(
private pageRepository: PageRepository,
private dataSource: DataSource,
@Inject(forwardRef(() => PageService))
private pageService: PageService,
@InjectKysely() private readonly db: KyselyDB,
) {}
async movePage(dto: MovePageDto): Promise<void> {
await this.dataSource.transaction(async (manager: EntityManager) => {
const movedPageId = dto.id;
// TODO: scope to workspace and space
const movedPage = await manager
.createQueryBuilder(Page, 'page')
.where('page.id = :movedPageId', { movedPageId })
.select(['page.id', 'page.spaceId', 'page.parentPageId'])
.getOne();
async movePage(dto: MovePageDto, trx?: KyselyTransaction): Promise<void> {
await executeTx(
this.db,
async (trx) => {
const movedPageId = dto.pageId;
if (!movedPage) throw new BadRequestException('Moved page not found');
const movedPage = await trx
.selectFrom('pages as page')
.select(['page.id', 'page.spaceId', 'page.parentPageId'])
.where('page.id', '=', movedPageId)
.executeTakeFirst();
if (!dto.parentId) {
if (movedPage.parentPageId) {
await this.removeFromParent(movedPage.parentPageId, dto.id, manager);
}
const spaceOrdering = await this.getEntityOrdering(
movedPage.spaceId,
OrderingEntity.space,
manager,
);
if (!movedPage) throw new NotFoundException('Moved page not found');
orderPageList(spaceOrdering.childrenIds, dto);
// if no parentId, it means the page is a root page or now a root page
if (!dto.parentId) {
// if it had a parent before being moved, we detach it from the previous parent
if (movedPage.parentPageId) {
await this.removeFromParent(
movedPage.parentPageId,
dto.pageId,
trx,
);
}
const spaceOrdering = await this.getEntityOrdering(
movedPage.spaceId,
OrderingEntity.SPACE,
trx,
);
await manager.save(spaceOrdering);
} else {
const parentPageId = dto.parentId;
orderPageList(spaceOrdering.childrenIds, dto);
// it should save or update right?
// await manager.save(spaceOrdering); //TODO: to update or create new record? pretty confusing
await trx
.updateTable('page_ordering')
.set(spaceOrdering)
.where('id', '=', spaceOrdering.id)
.execute();
} else {
const parentPageId = dto.parentId;
let parentPageOrdering = await this.getEntityOrdering(
parentPageId,
OrderingEntity.page,
manager,
);
if (!parentPageOrdering) {
parentPageOrdering = await this.createPageOrdering(
let parentPageOrdering = await this.getEntityOrdering(
parentPageId,
OrderingEntity.page,
movedPage.spaceId,
manager,
OrderingEntity.PAGE,
trx,
);
if (!parentPageOrdering) {
parentPageOrdering = await this.createPageOrdering(
parentPageId,
OrderingEntity.PAGE,
movedPage.spaceId,
trx,
);
}
// Check if the parent was changed
if (
movedPage.parentPageId &&
movedPage.parentPageId !== parentPageId
) {
//if yes, remove moved page from old parent's children
await this.removeFromParent(
movedPage.parentPageId,
dto.pageId,
trx,
);
}
// If movedPage didn't have a parent initially (was at root level), update the root level
if (!movedPage.parentPageId) {
await this.removeFromSpacePageOrder(
movedPage.spaceId,
dto.pageId,
trx,
);
}
// Modify the children list of the new parentPage and save
orderPageList(parentPageOrdering.childrenIds, dto);
await trx
.updateTable('page_ordering')
.set(parentPageOrdering)
.where('id', '=', parentPageOrdering.id)
.execute();
}
// Check if the parent was changed
if (movedPage.parentPageId && movedPage.parentPageId !== parentPageId) {
//if yes, remove moved page from old parent's children
await this.removeFromParent(movedPage.parentPageId, dto.id, manager);
}
// If movedPage didn't have a parent initially (was at root level), update the root level
if (!movedPage.parentPageId) {
await this.removeFromSpacePageOrder(
movedPage.spaceId,
dto.id,
manager,
);
}
// Modify the children list of the new parentPage and save
orderPageList(parentPageOrdering.childrenIds, dto);
await manager.save(parentPageOrdering);
}
movedPage.parentPageId = dto.parentId || null;
await manager.save(movedPage);
});
// update the parent Id of the moved page
await trx
.updateTable('pages')
.set({
parentPageId: movedPage.parentPageId || null,
})
.where('id', '=', movedPage.id)
.execute();
},
trx,
);
}
async addPageToOrder(spaceId: string, pageId: string, parentPageId?: string) {
await this.dataSource.transaction(async (manager: EntityManager) => {
if (parentPageId) {
await this.upsertOrdering(
parentPageId,
OrderingEntity.page,
pageId,
spaceId,
manager,
);
} else {
await this.addToSpacePageOrder(spaceId, pageId, manager);
}
});
async addPageToOrder(
spaceId: string,
pageId: string,
parentPageId?: string,
trx?: KyselyTransaction,
) {
await executeTx(
this.db,
async (trx: KyselyTransaction) => {
if (parentPageId) {
await this.upsertOrdering(
parentPageId,
OrderingEntity.PAGE,
pageId,
spaceId,
trx,
);
} else {
await this.addToSpacePageOrder(spaceId, pageId, trx);
}
},
trx,
);
}
async addToSpacePageOrder(
spaceId: string,
pageId: string,
manager: EntityManager,
trx: KyselyTransaction,
) {
await this.upsertOrdering(
spaceId,
OrderingEntity.space,
OrderingEntity.SPACE,
pageId,
spaceId,
manager,
trx,
);
}
async removeFromParent(
parentId: string,
childId: string,
manager: EntityManager,
trx: KyselyTransaction,
): Promise<void> {
await this.removeChildFromOrdering(
parentId,
OrderingEntity.page,
OrderingEntity.PAGE,
childId,
manager,
trx,
);
}
async removeFromSpacePageOrder(
spaceId: string,
pageId: string,
manager: EntityManager,
trx: KyselyTransaction,
) {
await this.removeChildFromOrdering(
spaceId,
OrderingEntity.space,
OrderingEntity.SPACE,
pageId,
manager,
trx,
);
}
@ -155,27 +197,23 @@ export class PageOrderingService {
entityId: string,
entityType: string,
childId: string,
manager: EntityManager,
trx: KyselyTransaction,
): Promise<void> {
const ordering = await this.getEntityOrdering(
entityId,
entityType,
manager,
);
const ordering = await this.getEntityOrdering(entityId, entityType, trx);
if (ordering && ordering.childrenIds.includes(childId)) {
await removeFromArrayAndSave(ordering, 'childrenIds', childId, manager);
await removeFromArrayAndSave(ordering, 'childrenIds', childId, trx);
}
}
async removePageFromHierarchy(
page: Page,
manager: EntityManager,
trx: KyselyTransaction,
): Promise<void> {
if (page.parentPageId) {
await this.removeFromParent(page.parentPageId, page.id, manager);
await this.removeFromParent(page.parentPageId, page.id, trx);
} else {
await this.removeFromSpacePageOrder(page.spaceId, page.id, manager);
await this.removeFromSpacePageOrder(page.spaceId, page.id, trx);
}
}
@ -184,65 +222,74 @@ export class PageOrderingService {
entityType: string,
childId: string,
spaceId: string,
manager: EntityManager,
trx: KyselyTransaction,
) {
let ordering = await this.getEntityOrdering(entityId, entityType, manager);
let ordering = await this.getEntityOrdering(entityId, entityType, trx);
if (!ordering) {
ordering = await this.createPageOrdering(
entityId,
entityType,
spaceId,
manager,
trx,
);
}
if (!ordering.childrenIds.includes(childId)) {
ordering.childrenIds.unshift(childId);
await manager.save(PageOrdering, ordering);
await trx
.updateTable('page_ordering')
.set(ordering)
.where('id', '=', ordering.id)
.execute();
//await manager.save(PageOrdering, ordering);
}
}
async getEntityOrdering(
entityId: string,
entityType: string,
manager,
trx: KyselyTransaction,
): Promise<PageOrdering> {
return manager
.createQueryBuilder(PageOrdering, 'ordering')
.setLock('pessimistic_write')
.where('ordering.entityId = :entityId', { entityId })
.andWhere('ordering.entityType = :entityType', {
entityType,
})
.getOne();
return trx
.selectFrom('page_ordering')
.selectAll()
.where('entityId', '=', entityId)
.where('entityType', '=', entityType)
.forUpdate()
.executeTakeFirst();
}
async createPageOrdering(
entityId: string,
entityType: string,
spaceId: string,
manager: EntityManager,
trx: KyselyTransaction,
): Promise<PageOrdering> {
await manager.query(
`INSERT INTO page_ordering ("entityId", "entityType", "spaceId", "childrenIds")
VALUES ($1, $2, $3, '{}')
ON CONFLICT ("entityId", "entityType") DO NOTHING`,
[entityId, entityType, spaceId],
);
await trx
.insertInto('page_ordering')
.values({
entityId,
entityType,
spaceId,
childrenIds: [],
})
.onConflict((oc) => oc.columns(['entityId', 'entityType']).doNothing())
.execute();
return await this.getEntityOrdering(entityId, entityType, manager);
// Todo: maybe use returning above
return await this.getEntityOrdering(entityId, entityType, trx);
}
async getSpacePageOrder(spaceId: string): Promise<PageOrdering> {
return await this.dataSource
.createQueryBuilder(PageOrdering, 'ordering')
.select(['ordering.id', 'ordering.childrenIds', 'ordering.spaceId'])
.where('ordering.entityId = :spaceId', { spaceId })
.andWhere('ordering.entityType = :entityType', {
entityType: OrderingEntity.space,
})
.getOne();
async getSpacePageOrder(
spaceId: string,
): Promise<{ id: string; childrenIds: string[]; spaceId: string }> {
return await this.db
.selectFrom('page_ordering')
.select(['id', 'childrenIds', 'spaceId'])
.where('entityId', '=', spaceId)
.where('entityType', '=', OrderingEntity.SPACE)
.executeTakeFirst();
}
async convertToTree(spaceId: string): Promise<TreeNode[]> {

View File

@ -1,59 +1,34 @@
import {
BadRequestException,
forwardRef,
Inject,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { PageRepository } from '../repositories/page.repository';
import { CreatePageDto } from '../dto/create-page.dto';
import { Page } from '../entities/page.entity';
import { UpdatePageDto } from '../dto/update-page.dto';
import { plainToInstance } from 'class-transformer';
import { DataSource, EntityManager } from 'typeorm';
import { PageOrderingService } from './page-ordering.service';
import { PageWithOrderingDto } from '../dto/page-with-ordering.dto';
import { OrderingEntity, transformPageResult } from '../page.util';
import { transformPageResult } from '../page.util';
import { PageRepo } from '@docmost/db/repos/page/page.repo';
import { Page } from '@docmost/db/types/entity.types';
import { PaginationOptions } from 'src/helpers/pagination/pagination-options';
import { PaginationMetaDto } from 'src/helpers/pagination/pagination-meta-dto';
import { PaginatedResult } from 'src/helpers/pagination/paginated-result';
@Injectable()
export class PageService {
constructor(
private pageRepository: PageRepository,
private dataSource: DataSource,
private pageRepo: PageRepo,
@Inject(forwardRef(() => PageOrderingService))
private pageOrderingService: PageOrderingService,
) {}
async findWithBasic(pageId: string) {
return this.pageRepository.findOne({
where: { id: pageId },
select: ['id', 'title'],
});
}
async findById(pageId: string) {
return this.pageRepository.findById(pageId);
}
async findWithContent(pageId: string) {
return this.pageRepository.findWithContent(pageId);
}
async findWithYdoc(pageId: string) {
return this.pageRepository.findWithYDoc(pageId);
}
async findWithAllFields(pageId: string) {
return this.pageRepository.findWithAllFields(pageId);
}
async findOne(pageId: string): Promise<Page> {
const page = await this.findById(pageId);
if (!page) {
throw new BadRequestException('Page not found');
}
return page;
async findById(
pageId: string,
includeContent?: boolean,
includeYdoc?: boolean,
): Promise<Page> {
return this.pageRepo.findById(pageId, includeContent, includeYdoc);
}
async create(
@ -61,26 +36,26 @@ export class PageService {
workspaceId: string,
createPageDto: CreatePageDto,
): Promise<Page> {
const page = plainToInstance(Page, createPageDto);
page.creatorId = userId;
page.workspaceId = workspaceId;
page.lastUpdatedById = userId;
// check if parent page exists
if (createPageDto.parentPageId) {
// TODO: make sure parent page belongs to same space and user has permissions
const parentPage = await this.pageRepository.findOne({
where: { id: createPageDto.parentPageId },
select: ['id'],
});
if (!parentPage) throw new BadRequestException('Parent page not found');
const parentPage = await this.pageRepo.findById(
createPageDto.parentPageId,
);
if (!parentPage) throw new NotFoundException('Parent page not found');
}
const createdPage = await this.pageRepository.save(page);
//TODO: should be in a transaction
const createdPage = await this.pageRepo.insertPage({
...createPageDto,
creatorId: userId,
workspaceId: workspaceId,
lastUpdatedById: userId,
});
await this.pageOrderingService.addPageToOrder(
createPageDto.spaceId,
createPageDto.id,
createPageDto.pageId,
createPageDto.parentPageId,
);
@ -91,18 +66,16 @@ export class PageService {
pageId: string,
updatePageDto: UpdatePageDto,
userId: string,
): Promise<Page> {
const updateData = {
...updatePageDto,
lastUpdatedById: userId,
};
): Promise<void> {
await this.pageRepo.updatePage(
{
...updatePageDto,
lastUpdatedById: userId,
},
pageId,
);
const result = await this.pageRepository.update(pageId, updateData);
if (result.affected === 0) {
throw new BadRequestException(`Page not found`);
}
return await this.pageRepository.findById(pageId);
//return await this.pageRepo.findById(pageId);
}
async updateState(
@ -112,14 +85,19 @@ export class PageService {
ydoc: any,
userId?: string, // TODO: fix this
): Promise<void> {
await this.pageRepository.update(pageId, {
content: content,
textContent: textContent,
ydoc: ydoc,
...(userId && { lastUpdatedById: userId }),
});
await this.pageRepo.updatePage(
{
content: content,
textContent: textContent,
ydoc: ydoc,
...(userId && { lastUpdatedById: userId }),
},
pageId,
);
}
/*
// TODO: page deletion and restoration
async delete(pageId: string): Promise<void> {
await this.dataSource.transaction(async (manager: EntityManager) => {
const page = await manager
@ -207,59 +185,30 @@ export class PageService {
await manager.recover(Page, { id: child.id });
}
}
*/
async forceDelete(pageId: string): Promise<void> {
await this.pageRepository.delete(pageId);
}
async lockOrUnlockPage(pageId: string, lock: boolean): Promise<Page> {
await this.pageRepository.update(pageId, { isLocked: lock });
return await this.pageRepository.findById(pageId);
await this.pageRepo.deletePage(pageId);
}
async getSidebarPagesBySpaceId(
spaceId: string,
limit = 200,
): Promise<PageWithOrderingDto[]> {
const pages = await this.pageRepository
.createQueryBuilder('page')
.leftJoin(
'page_ordering',
'ordering',
'ordering.entityId = page.id AND ordering.entityType = :entityType',
{ entityType: OrderingEntity.page },
)
.where('page.spaceId = :spaceId', { spaceId })
.select([
'page.id',
'page.title',
'page.icon',
'page.parentPageId',
'page.spaceId',
'ordering.childrenIds',
'page.creatorId',
'page.createdAt',
])
.orderBy('page.createdAt', 'DESC')
.take(limit)
.getRawMany<PageWithOrderingDto[]>();
const pages = await this.pageRepo.getSpaceSidebarPages(spaceId, limit);
return transformPageResult(pages);
}
async getRecentSpacePages(
spaceId: string,
limit = 20,
offset = 0,
): Promise<Page[]> {
const pages = await this.pageRepository
.createQueryBuilder('page')
.where('page.spaceId = :spaceId', { spaceId })
.select(this.pageRepository.baseFields)
.orderBy('page.updatedAt', 'DESC')
.offset(offset)
.take(limit)
.getMany();
return pages;
paginationOptions: PaginationOptions,
): Promise<PaginatedResult<Page>> {
const { pages, count } = await this.pageRepo.getRecentPagesInSpace(
spaceId,
paginationOptions,
);
const paginationMeta = new PaginationMetaDto({ count, paginationOptions });
return new PaginatedResult(pages, paginationMeta);
}
}