mirror of
https://github.com/Shadowfita/docmost.git
synced 2025-11-24 13:41:02 +10:00
switch to nx monorepo
This commit is contained in:
61
apps/server/src/core/page/services/page-history.service.ts
Normal file
61
apps/server/src/core/page/services/page-history.service.ts
Normal file
@ -0,0 +1,61 @@
|
||||
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';
|
||||
|
||||
@Injectable()
|
||||
export class PageHistoryService {
|
||||
constructor(private pageHistoryRepo: PageHistoryRepository) {
|
||||
}
|
||||
|
||||
async findOne(historyId: string): Promise<PageHistory> {
|
||||
const history = await this.pageHistoryRepo.findById(historyId);
|
||||
if (!history) {
|
||||
throw new BadRequestException('History not found');
|
||||
}
|
||||
return history;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
292
apps/server/src/core/page/services/page-ordering.service.ts
Normal file
292
apps/server/src/core/page/services/page-ordering.service.ts
Normal file
@ -0,0 +1,292 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
forwardRef,
|
||||
Inject,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { PageRepository } from '../repositories/page.repository';
|
||||
import { Page } from '../entities/page.entity';
|
||||
import { MovePageDto } from '../dto/move-page.dto';
|
||||
import {
|
||||
OrderingEntity,
|
||||
orderPageList,
|
||||
removeFromArrayAndSave,
|
||||
TreeNode,
|
||||
} from '../page.util';
|
||||
import { DataSource, EntityManager } from 'typeorm';
|
||||
import { PageService } from './page.service';
|
||||
import { PageOrdering } from '../entities/page-ordering.entity';
|
||||
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,
|
||||
) {}
|
||||
|
||||
async movePage(dto: MovePageDto): Promise<void> {
|
||||
await this.dataSource.transaction(async (manager: EntityManager) => {
|
||||
const movedPageId = dto.id;
|
||||
|
||||
const movedPage = await manager
|
||||
.createQueryBuilder(Page, 'page')
|
||||
.where('page.id = :movedPageId', { movedPageId })
|
||||
.select(['page.id', 'page.workspaceId', 'page.parentPageId'])
|
||||
.getOne();
|
||||
|
||||
if (!movedPage) throw new BadRequestException('Moved page not found');
|
||||
|
||||
if (!dto.parentId) {
|
||||
if (movedPage.parentPageId) {
|
||||
await this.removeFromParent(movedPage.parentPageId, dto.id, manager);
|
||||
}
|
||||
const workspaceOrdering = await this.getEntityOrdering(
|
||||
movedPage.workspaceId,
|
||||
OrderingEntity.workspace,
|
||||
manager,
|
||||
);
|
||||
|
||||
orderPageList(workspaceOrdering.childrenIds, dto);
|
||||
|
||||
await manager.save(workspaceOrdering);
|
||||
} else {
|
||||
const parentPageId = dto.parentId;
|
||||
|
||||
let parentPageOrdering = await this.getEntityOrdering(
|
||||
parentPageId,
|
||||
OrderingEntity.page,
|
||||
manager,
|
||||
);
|
||||
|
||||
if (!parentPageOrdering) {
|
||||
parentPageOrdering = await this.createPageOrdering(
|
||||
parentPageId,
|
||||
OrderingEntity.page,
|
||||
movedPage.workspaceId,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
|
||||
// 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.removeFromWorkspacePageOrder(
|
||||
movedPage.workspaceId,
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
async addPageToOrder(
|
||||
workspaceId: string,
|
||||
pageId: string,
|
||||
parentPageId?: string,
|
||||
) {
|
||||
await this.dataSource.transaction(async (manager: EntityManager) => {
|
||||
if (parentPageId) {
|
||||
await this.upsertOrdering(
|
||||
parentPageId,
|
||||
OrderingEntity.page,
|
||||
pageId,
|
||||
workspaceId,
|
||||
manager,
|
||||
);
|
||||
} else {
|
||||
await this.addToWorkspacePageOrder(workspaceId, pageId, manager);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async addToWorkspacePageOrder(
|
||||
workspaceId: string,
|
||||
pageId: string,
|
||||
manager: EntityManager,
|
||||
) {
|
||||
await this.upsertOrdering(
|
||||
workspaceId,
|
||||
OrderingEntity.workspace,
|
||||
pageId,
|
||||
workspaceId,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
|
||||
async removeFromParent(
|
||||
parentId: string,
|
||||
childId: string,
|
||||
manager: EntityManager,
|
||||
): Promise<void> {
|
||||
await this.removeChildFromOrdering(
|
||||
parentId,
|
||||
OrderingEntity.page,
|
||||
childId,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
|
||||
async removeFromWorkspacePageOrder(
|
||||
workspaceId: string,
|
||||
pageId: string,
|
||||
manager: EntityManager,
|
||||
) {
|
||||
await this.removeChildFromOrdering(
|
||||
workspaceId,
|
||||
OrderingEntity.workspace,
|
||||
pageId,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
|
||||
async removeChildFromOrdering(
|
||||
entityId: string,
|
||||
entityType: string,
|
||||
childId: string,
|
||||
manager: EntityManager,
|
||||
): Promise<void> {
|
||||
const ordering = await this.getEntityOrdering(
|
||||
entityId,
|
||||
entityType,
|
||||
manager,
|
||||
);
|
||||
|
||||
if (ordering && ordering.childrenIds.includes(childId)) {
|
||||
await removeFromArrayAndSave(ordering, 'childrenIds', childId, manager);
|
||||
}
|
||||
}
|
||||
|
||||
async removePageFromHierarchy(
|
||||
page: Page,
|
||||
manager: EntityManager,
|
||||
): Promise<void> {
|
||||
if (page.parentPageId) {
|
||||
await this.removeFromParent(page.parentPageId, page.id, manager);
|
||||
} else {
|
||||
await this.removeFromWorkspacePageOrder(
|
||||
page.workspaceId,
|
||||
page.id,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async upsertOrdering(
|
||||
entityId: string,
|
||||
entityType: string,
|
||||
childId: string,
|
||||
workspaceId: string,
|
||||
manager: EntityManager,
|
||||
) {
|
||||
let ordering = await this.getEntityOrdering(entityId, entityType, manager);
|
||||
|
||||
if (!ordering) {
|
||||
ordering = await this.createPageOrdering(
|
||||
entityId,
|
||||
entityType,
|
||||
workspaceId,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
|
||||
if (!ordering.childrenIds.includes(childId)) {
|
||||
ordering.childrenIds.unshift(childId);
|
||||
await manager.save(PageOrdering, ordering);
|
||||
}
|
||||
}
|
||||
|
||||
async getEntityOrdering(
|
||||
entityId: string,
|
||||
entityType: string,
|
||||
manager,
|
||||
): Promise<PageOrdering> {
|
||||
return manager
|
||||
.createQueryBuilder(PageOrdering, 'ordering')
|
||||
.setLock('pessimistic_write')
|
||||
.where('ordering.entityId = :entityId', { entityId })
|
||||
.andWhere('ordering.entityType = :entityType', {
|
||||
entityType,
|
||||
})
|
||||
.getOne();
|
||||
}
|
||||
|
||||
async createPageOrdering(
|
||||
entityId: string,
|
||||
entityType: string,
|
||||
workspaceId: string,
|
||||
manager: EntityManager,
|
||||
): Promise<PageOrdering> {
|
||||
await manager.query(
|
||||
`INSERT INTO page_ordering ("entityId", "entityType", "workspaceId", "childrenIds")
|
||||
VALUES ($1, $2, $3, '{}')
|
||||
ON CONFLICT ("entityId", "entityType") DO NOTHING`,
|
||||
[entityId, entityType, workspaceId],
|
||||
);
|
||||
|
||||
return await this.getEntityOrdering(entityId, entityType, manager);
|
||||
}
|
||||
|
||||
async getWorkspacePageOrder(workspaceId: string): Promise<PageOrdering> {
|
||||
return await this.dataSource
|
||||
.createQueryBuilder(PageOrdering, 'ordering')
|
||||
.select(['ordering.id', 'ordering.childrenIds', 'ordering.workspaceId'])
|
||||
.where('ordering.entityId = :workspaceId', { workspaceId })
|
||||
.andWhere('ordering.entityType = :entityType', {
|
||||
entityType: OrderingEntity.workspace,
|
||||
})
|
||||
.getOne();
|
||||
}
|
||||
|
||||
async convertToTree(workspaceId: string): Promise<TreeNode[]> {
|
||||
const workspaceOrder = await this.getWorkspacePageOrder(workspaceId);
|
||||
|
||||
const pageOrder = workspaceOrder ? workspaceOrder.childrenIds : undefined;
|
||||
const pages = await this.pageService.getSidebarPagesByWorkspaceId(workspaceId);
|
||||
|
||||
const pageMap: { [id: string]: PageWithOrderingDto } = {};
|
||||
pages.forEach((page) => {
|
||||
pageMap[page.id] = page;
|
||||
});
|
||||
|
||||
function buildTreeNode(id: string): TreeNode | undefined {
|
||||
const page = pageMap[id];
|
||||
if (!page) return;
|
||||
|
||||
const node: TreeNode = {
|
||||
id: page.id,
|
||||
title: page.title || '',
|
||||
children: [],
|
||||
};
|
||||
|
||||
if (page.icon) node.icon = page.icon;
|
||||
|
||||
if (page.childrenIds && page.childrenIds.length > 0) {
|
||||
node.children = page.childrenIds
|
||||
.map((childId) => buildTreeNode(childId))
|
||||
.filter(Boolean) as TreeNode[];
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
return pageOrder
|
||||
.map((id) => buildTreeNode(id))
|
||||
.filter(Boolean) as TreeNode[];
|
||||
}
|
||||
}
|
||||
18
apps/server/src/core/page/services/page.service.spec.ts
Normal file
18
apps/server/src/core/page/services/page.service.spec.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { PageService } from './page.service';
|
||||
|
||||
describe('PageService', () => {
|
||||
let service: PageService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [PageService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<PageService>(PageService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
267
apps/server/src/core/page/services/page.service.ts
Normal file
267
apps/server/src/core/page/services/page.service.ts
Normal file
@ -0,0 +1,267 @@
|
||||
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';
|
||||
|
||||
@Injectable()
|
||||
export class PageService {
|
||||
constructor(
|
||||
private pageRepository: PageRepository,
|
||||
private dataSource: DataSource,
|
||||
@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 create(
|
||||
userId: string,
|
||||
workspaceId: string,
|
||||
createPageDto: CreatePageDto,
|
||||
): Promise<Page> {
|
||||
const page = plainToInstance(Page, createPageDto);
|
||||
page.creatorId = userId;
|
||||
page.workspaceId = workspaceId;
|
||||
page.lastUpdatedById = userId;
|
||||
|
||||
if (createPageDto.parentPageId) {
|
||||
// TODO: make sure parent page belongs to same workspace 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 createdPage = await this.pageRepository.save(page);
|
||||
|
||||
await this.pageOrderingService.addPageToOrder(
|
||||
workspaceId,
|
||||
createPageDto.id,
|
||||
createPageDto.parentPageId,
|
||||
);
|
||||
|
||||
return createdPage;
|
||||
}
|
||||
|
||||
async update(
|
||||
pageId: string,
|
||||
updatePageDto: UpdatePageDto,
|
||||
userId: string,
|
||||
): Promise<Page> {
|
||||
const updateData = {
|
||||
...updatePageDto,
|
||||
lastUpdatedById: userId,
|
||||
};
|
||||
|
||||
const result = await this.pageRepository.update(pageId, updateData);
|
||||
if (result.affected === 0) {
|
||||
throw new BadRequestException(`Page not found`);
|
||||
}
|
||||
|
||||
return await this.pageRepository.findById(pageId);
|
||||
}
|
||||
|
||||
async updateState(
|
||||
pageId: string,
|
||||
content: any,
|
||||
ydoc: any,
|
||||
userId?: string, // TODO: fix this
|
||||
): Promise<void> {
|
||||
await this.pageRepository.update(pageId, {
|
||||
content: content,
|
||||
ydoc: ydoc,
|
||||
...(userId && { lastUpdatedById: userId }),
|
||||
});
|
||||
}
|
||||
|
||||
async delete(pageId: string): Promise<void> {
|
||||
await this.dataSource.transaction(async (manager: EntityManager) => {
|
||||
const page = await manager
|
||||
.createQueryBuilder(Page, 'page')
|
||||
.where('page.id = :pageId', { pageId })
|
||||
.select(['page.id', 'page.workspaceId'])
|
||||
.getOne();
|
||||
|
||||
if (!page) {
|
||||
throw new NotFoundException(`Page not found`);
|
||||
}
|
||||
await this.softDeleteChildrenRecursive(page.id, manager);
|
||||
await this.pageOrderingService.removePageFromHierarchy(page, manager);
|
||||
|
||||
await manager.softDelete(Page, pageId);
|
||||
});
|
||||
}
|
||||
|
||||
private async softDeleteChildrenRecursive(
|
||||
parentId: string,
|
||||
manager: EntityManager,
|
||||
): Promise<void> {
|
||||
const childrenPage = await manager
|
||||
.createQueryBuilder(Page, 'page')
|
||||
.where('page.parentPageId = :parentId', { parentId })
|
||||
.select(['page.id', 'page.title', 'page.parentPageId'])
|
||||
.getMany();
|
||||
|
||||
for (const child of childrenPage) {
|
||||
await this.softDeleteChildrenRecursive(child.id, manager);
|
||||
await manager.softDelete(Page, child.id);
|
||||
}
|
||||
}
|
||||
|
||||
async restore(pageId: string): Promise<void> {
|
||||
await this.dataSource.transaction(async (manager: EntityManager) => {
|
||||
const isDeleted = await manager
|
||||
.createQueryBuilder(Page, 'page')
|
||||
.where('page.id = :pageId', { pageId })
|
||||
.withDeleted()
|
||||
.getCount();
|
||||
|
||||
if (!isDeleted) {
|
||||
return;
|
||||
}
|
||||
|
||||
await manager.recover(Page, { id: pageId });
|
||||
|
||||
await this.restoreChildrenRecursive(pageId, manager);
|
||||
|
||||
// Fetch the page details to find out its parent and workspace
|
||||
const restoredPage = await manager
|
||||
.createQueryBuilder(Page, 'page')
|
||||
.where('page.id = :pageId', { pageId })
|
||||
.select([
|
||||
'page.id',
|
||||
'page.title',
|
||||
'page.workspaceId',
|
||||
'page.parentPageId',
|
||||
])
|
||||
.getOne();
|
||||
|
||||
if (!restoredPage) {
|
||||
throw new NotFoundException(`Restored page not found.`);
|
||||
}
|
||||
|
||||
// add page back to its hierarchy
|
||||
await this.pageOrderingService.addPageToOrder(
|
||||
restoredPage.workspaceId,
|
||||
pageId,
|
||||
restoredPage.parentPageId,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private async restoreChildrenRecursive(
|
||||
parentId: string,
|
||||
manager: EntityManager,
|
||||
): Promise<void> {
|
||||
const childrenPage = await manager
|
||||
.createQueryBuilder(Page, 'page')
|
||||
.setLock('pessimistic_write')
|
||||
.where('page.parentPageId = :parentId', { parentId })
|
||||
.select(['page.id', 'page.title', 'page.parentPageId'])
|
||||
.withDeleted()
|
||||
.getMany();
|
||||
|
||||
for (const child of childrenPage) {
|
||||
await this.restoreChildrenRecursive(child.id, manager);
|
||||
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);
|
||||
}
|
||||
|
||||
async getSidebarPagesByWorkspaceId(
|
||||
workspaceId: 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.workspaceId = :workspaceId', { workspaceId })
|
||||
.select([
|
||||
'page.id',
|
||||
'page.title',
|
||||
'page.icon',
|
||||
'page.parentPageId',
|
||||
'ordering.childrenIds',
|
||||
'page.creatorId',
|
||||
'page.createdAt',
|
||||
])
|
||||
.orderBy('page.createdAt', 'DESC')
|
||||
.take(limit)
|
||||
.getRawMany<PageWithOrderingDto[]>();
|
||||
|
||||
return transformPageResult(pages);
|
||||
}
|
||||
|
||||
async getRecentWorkspacePages(
|
||||
workspaceId: string,
|
||||
limit = 20,
|
||||
offset = 0,
|
||||
): Promise<Page[]> {
|
||||
const pages = await this.pageRepository
|
||||
.createQueryBuilder('page')
|
||||
.where('page.workspaceId = :workspaceId', { workspaceId })
|
||||
.select(this.pageRepository.baseFields)
|
||||
.orderBy('page.updatedAt', 'DESC')
|
||||
.offset(offset)
|
||||
.take(limit)
|
||||
.getMany();
|
||||
return pages;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user