mirror of
https://github.com/Shadowfita/docmost.git
synced 2025-11-13 00:02:30 +10:00
Rework sidebar pages
* Move sidebar pages from workspace to space level * Replace array sorting with lexicographical fractional indexing * Fixes and updates
This commit is contained in:
@ -1,10 +1,6 @@
|
||||
import { IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
|
||||
export class CreatePageDto {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
pageId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
title?: string;
|
||||
|
||||
@ -1,18 +1,21 @@
|
||||
import { IsString, IsOptional, IsUUID } from 'class-validator';
|
||||
import {
|
||||
IsString,
|
||||
IsUUID,
|
||||
IsOptional,
|
||||
MinLength,
|
||||
MaxLength,
|
||||
} from 'class-validator';
|
||||
|
||||
export class MovePageDto {
|
||||
@IsUUID()
|
||||
pageId: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
after?: string;
|
||||
@MinLength(5)
|
||||
@MaxLength(12)
|
||||
position: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
before?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
parentId?: string | null;
|
||||
parentPageId?: string | null;
|
||||
}
|
||||
|
||||
8
apps/server/src/core/page/dto/sidebar-page.dto.ts
Normal file
8
apps/server/src/core/page/dto/sidebar-page.dto.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { IsOptional, IsUUID } from 'class-validator';
|
||||
import { SpaceIdDto } from './page.dto';
|
||||
|
||||
export class SidebarPageDto extends SpaceIdDto {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
pageId: string;
|
||||
}
|
||||
@ -11,36 +11,29 @@ import { CreatePageDto } from './dto/create-page.dto';
|
||||
import { UpdatePageDto } from './dto/update-page.dto';
|
||||
import { MovePageDto } from './dto/move-page.dto';
|
||||
import { PageHistoryIdDto, PageIdDto, SpaceIdDto } from './dto/page.dto';
|
||||
import { PageOrderingService } from './services/page-ordering.service';
|
||||
import { PageHistoryService } from './services/page-history.service';
|
||||
import { AuthUser } from '../../decorators/auth-user.decorator';
|
||||
import { AuthWorkspace } from '../../decorators/auth-workspace.decorator';
|
||||
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
|
||||
import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
|
||||
import { User, Workspace } from '@docmost/db/types/entity.types';
|
||||
import { SidebarPageDto } from './dto/sidebar-page.dto';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('pages')
|
||||
export class PageController {
|
||||
constructor(
|
||||
private readonly pageService: PageService,
|
||||
private readonly pageOrderService: PageOrderingService,
|
||||
private readonly pageHistoryService: PageHistoryService,
|
||||
) {}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post()
|
||||
async getSpacePages(@Body() spaceIdDto: SpaceIdDto) {
|
||||
return this.pageService.getSidebarPagesBySpaceId(spaceIdDto.spaceId);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('/info')
|
||||
async getPage(@Body() pageIdDto: PageIdDto) {
|
||||
return this.pageService.findById(pageIdDto.pageId);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('create')
|
||||
async create(
|
||||
@Body() createPageDto: CreatePageDto,
|
||||
@ -72,12 +65,6 @@ export class PageController {
|
||||
// await this.pageService.restore(deletePageDto.id);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('move')
|
||||
async movePage(@Body() movePageDto: MovePageDto) {
|
||||
return this.pageOrderService.movePage(movePageDto);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('recent')
|
||||
async getRecentSpacePages(
|
||||
@ -87,18 +74,6 @@ export class PageController {
|
||||
return this.pageService.getRecentSpacePages(spaceIdDto.spaceId, pagination);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('ordering')
|
||||
async getSpacePageOrder(@Body() spaceIdDto: SpaceIdDto) {
|
||||
return this.pageOrderService.getSpacePageOrder(spaceIdDto.spaceId);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('tree')
|
||||
async spacePageTree(@Body() spaceIdDto: SpaceIdDto) {
|
||||
return this.pageOrderService.convertToTree(spaceIdDto.spaceId);
|
||||
}
|
||||
|
||||
// TODO: scope to workspaces
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('/history')
|
||||
@ -111,7 +86,22 @@ export class PageController {
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('/history/details')
|
||||
async get(@Body() dto: PageHistoryIdDto) {
|
||||
async getPageHistoryInfo(@Body() dto: PageHistoryIdDto) {
|
||||
return this.pageHistoryService.findById(dto.historyId);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('/sidebar-pages')
|
||||
async getSidebarPages(
|
||||
@Body() dto: SidebarPageDto,
|
||||
@Body() pagination: PaginationOptions,
|
||||
) {
|
||||
return this.pageService.getSidebarPages(dto, pagination);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('move')
|
||||
async movePage(@Body() movePageDto: MovePageDto) {
|
||||
return this.pageService.movePage(movePageDto);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,13 +2,12 @@ import { Module } from '@nestjs/common';
|
||||
import { PageService } from './services/page.service';
|
||||
import { PageController } from './page.controller';
|
||||
import { WorkspaceModule } from '../workspace/workspace.module';
|
||||
import { PageOrderingService } from './services/page-ordering.service';
|
||||
import { PageHistoryService } from './services/page-history.service';
|
||||
|
||||
@Module({
|
||||
imports: [WorkspaceModule],
|
||||
controllers: [PageController],
|
||||
providers: [PageService, PageOrderingService, PageHistoryService],
|
||||
exports: [PageService, PageOrderingService, PageHistoryService],
|
||||
providers: [PageService, PageHistoryService],
|
||||
exports: [PageService, PageHistoryService],
|
||||
})
|
||||
export class PageModule {}
|
||||
|
||||
@ -1,87 +0,0 @@
|
||||
import { KyselyTransaction } from '@docmost/db/types/kysely.types';
|
||||
import { MovePageDto } from './dto/move-page.dto';
|
||||
import { PageOrdering } from '@docmost/db/types/entity.types';
|
||||
|
||||
export enum OrderingEntity {
|
||||
WORKSPACE = 'WORKSPACE',
|
||||
SPACE = 'SPACE',
|
||||
PAGE = 'PAGE',
|
||||
}
|
||||
|
||||
export type TreeNode = {
|
||||
id: string;
|
||||
title: string;
|
||||
icon?: string;
|
||||
children?: TreeNode[];
|
||||
};
|
||||
|
||||
export function orderPageList(arr: string[], payload: MovePageDto): void {
|
||||
const { pageId: id, after, before } = payload;
|
||||
|
||||
// Removing the item we are moving from the array first.
|
||||
const index = arr.indexOf(id);
|
||||
if (index > -1) arr.splice(index, 1);
|
||||
|
||||
if (after) {
|
||||
const afterIndex = arr.indexOf(after);
|
||||
if (afterIndex > -1) {
|
||||
arr.splice(afterIndex + 1, 0, id);
|
||||
} else {
|
||||
// Place the item at the end if the after ID is not found.
|
||||
arr.push(id);
|
||||
}
|
||||
} else if (before) {
|
||||
const beforeIndex = arr.indexOf(before);
|
||||
if (beforeIndex > -1) {
|
||||
arr.splice(beforeIndex, 0, id);
|
||||
} else {
|
||||
// Place the item at the end if the before ID is not found.
|
||||
arr.push(id);
|
||||
}
|
||||
} else {
|
||||
// If neither after nor before is provided, just add the id at the end
|
||||
if (!arr.includes(id)) {
|
||||
arr.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(
|
||||
entity: PageOrdering,
|
||||
arrayField: string,
|
||||
itemToRemove: any,
|
||||
trx: KyselyTransaction,
|
||||
) {
|
||||
const array = entity[arrayField];
|
||||
const index = array.indexOf(itemToRemove);
|
||||
if (index > -1) {
|
||||
array.splice(index, 1);
|
||||
await trx
|
||||
.updateTable('pageOrdering')
|
||||
.set(entity)
|
||||
.where('id', '=', entity.id)
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
|
||||
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 (key === 'childrenIds' && !row[key]) {
|
||||
processedRow[key] = [];
|
||||
} else {
|
||||
processedRow[key] = row[key];
|
||||
}
|
||||
}
|
||||
return processedRow;
|
||||
});
|
||||
}
|
||||
@ -1,332 +0,0 @@
|
||||
import {
|
||||
forwardRef,
|
||||
Inject,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { MovePageDto } from '../dto/move-page.dto';
|
||||
import {
|
||||
OrderingEntity,
|
||||
orderPageList,
|
||||
removeFromArrayAndSave,
|
||||
TreeNode,
|
||||
} from '../page.util';
|
||||
import { PageService } from './page.service';
|
||||
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(
|
||||
@Inject(forwardRef(() => PageService))
|
||||
private pageService: PageService,
|
||||
@InjectKysely() private readonly db: KyselyDB,
|
||||
) {}
|
||||
|
||||
// TODO: scope to workspace and space
|
||||
async movePage(dto: MovePageDto, trx?: KyselyTransaction): Promise<void> {
|
||||
await executeTx(
|
||||
this.db,
|
||||
async (trx) => {
|
||||
const movedPageId = dto.pageId;
|
||||
|
||||
const movedPage = await trx
|
||||
.selectFrom('pages as page')
|
||||
.select(['page.id', 'page.spaceId', 'page.parentPageId'])
|
||||
.where('page.id', '=', movedPageId)
|
||||
.executeTakeFirst();
|
||||
|
||||
if (!movedPage) throw new NotFoundException('Moved page not found');
|
||||
|
||||
// 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,
|
||||
);
|
||||
|
||||
orderPageList(spaceOrdering.childrenIds, dto);
|
||||
await trx
|
||||
.updateTable('pageOrdering')
|
||||
.set(spaceOrdering)
|
||||
.where('id', '=', spaceOrdering.id)
|
||||
.execute();
|
||||
} else {
|
||||
const parentPageId = dto.parentId;
|
||||
|
||||
let parentPageOrdering = await this.getEntityOrdering(
|
||||
parentPageId,
|
||||
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('pageOrdering')
|
||||
.set(parentPageOrdering)
|
||||
.where('id', '=', parentPageOrdering.id)
|
||||
.execute();
|
||||
}
|
||||
|
||||
// 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,
|
||||
trx?: KyselyTransaction,
|
||||
) {
|
||||
await executeTx(
|
||||
this.db,
|
||||
async (trx: KyselyTransaction) => {
|
||||
if (parentPageId) {
|
||||
await this.upsertOrdering(
|
||||
parentPageId,
|
||||
OrderingEntity.PAGE,
|
||||
pageId,
|
||||
spaceId,
|
||||
trx,
|
||||
);
|
||||
} else {
|
||||
await this.addToSpacePageOrder(pageId, spaceId, trx);
|
||||
}
|
||||
},
|
||||
trx,
|
||||
);
|
||||
}
|
||||
|
||||
async addToSpacePageOrder(
|
||||
pageId: string,
|
||||
spaceId: string,
|
||||
trx: KyselyTransaction,
|
||||
) {
|
||||
await this.upsertOrdering(
|
||||
spaceId,
|
||||
OrderingEntity.SPACE,
|
||||
pageId,
|
||||
spaceId,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
|
||||
async upsertOrdering(
|
||||
entityId: string,
|
||||
entityType: string,
|
||||
childId: string,
|
||||
spaceId: string,
|
||||
trx: KyselyTransaction,
|
||||
) {
|
||||
let ordering = await this.getEntityOrdering(entityId, entityType, trx);
|
||||
console.log(ordering);
|
||||
console.log('oga1');
|
||||
|
||||
if (!ordering) {
|
||||
ordering = await this.createPageOrdering(
|
||||
entityId,
|
||||
entityType,
|
||||
spaceId,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
|
||||
if (!ordering.childrenIds.includes(childId)) {
|
||||
ordering.childrenIds.unshift(childId);
|
||||
console.log(childId);
|
||||
console.log('childId above');
|
||||
await trx
|
||||
.updateTable('pageOrdering')
|
||||
.set(ordering)
|
||||
.where('id', '=', ordering.id)
|
||||
.execute();
|
||||
//await manager.save(PageOrdering, ordering);
|
||||
}
|
||||
}
|
||||
|
||||
async removeFromParent(
|
||||
parentId: string,
|
||||
childId: string,
|
||||
trx: KyselyTransaction,
|
||||
): Promise<void> {
|
||||
await this.removeChildFromOrdering(
|
||||
parentId,
|
||||
OrderingEntity.PAGE,
|
||||
childId,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
|
||||
async removeFromSpacePageOrder(
|
||||
spaceId: string,
|
||||
pageId: string,
|
||||
trx: KyselyTransaction,
|
||||
) {
|
||||
await this.removeChildFromOrdering(
|
||||
spaceId,
|
||||
OrderingEntity.SPACE,
|
||||
pageId,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
|
||||
async removeChildFromOrdering(
|
||||
entityId: string,
|
||||
entityType: string,
|
||||
childId: string,
|
||||
trx: KyselyTransaction,
|
||||
): Promise<void> {
|
||||
const ordering = await this.getEntityOrdering(entityId, entityType, trx);
|
||||
|
||||
if (ordering && ordering.childrenIds.includes(childId)) {
|
||||
await removeFromArrayAndSave(ordering, 'childrenIds', childId, trx);
|
||||
}
|
||||
}
|
||||
|
||||
async removePageFromHierarchy(
|
||||
page: Page,
|
||||
trx: KyselyTransaction,
|
||||
): Promise<void> {
|
||||
if (page.parentPageId) {
|
||||
await this.removeFromParent(page.parentPageId, page.id, trx);
|
||||
} else {
|
||||
await this.removeFromSpacePageOrder(page.spaceId, page.id, trx);
|
||||
}
|
||||
}
|
||||
|
||||
async getEntityOrdering(
|
||||
entityId: string,
|
||||
entityType: string,
|
||||
trx: KyselyTransaction,
|
||||
): Promise<PageOrdering> {
|
||||
return trx
|
||||
.selectFrom('pageOrdering')
|
||||
.selectAll()
|
||||
.where('entityId', '=', entityId)
|
||||
.where('entityType', '=', entityType)
|
||||
.forUpdate()
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
async createPageOrdering(
|
||||
entityId: string,
|
||||
entityType: string,
|
||||
spaceId: string,
|
||||
trx: KyselyTransaction,
|
||||
): Promise<PageOrdering> {
|
||||
await trx
|
||||
.insertInto('pageOrdering')
|
||||
.values({
|
||||
entityId,
|
||||
entityType,
|
||||
spaceId,
|
||||
childrenIds: [],
|
||||
})
|
||||
.onConflict((oc) => oc.columns(['entityId', 'entityType']).doNothing())
|
||||
.execute();
|
||||
|
||||
// Todo: maybe use returning above
|
||||
return await this.getEntityOrdering(entityId, entityType, trx);
|
||||
}
|
||||
|
||||
async getSpacePageOrder(
|
||||
spaceId: string,
|
||||
): Promise<{ id: string; childrenIds: string[]; spaceId: string }> {
|
||||
return await this.db
|
||||
.selectFrom('pageOrdering')
|
||||
.select(['id', 'childrenIds', 'spaceId'])
|
||||
.where('entityId', '=', spaceId)
|
||||
.where('entityType', '=', OrderingEntity.SPACE)
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
async convertToTree(spaceId: string): Promise<TreeNode[]> {
|
||||
const spaceOrder = await this.getSpacePageOrder(spaceId);
|
||||
|
||||
const pageOrder = spaceOrder ? spaceOrder.childrenIds : undefined;
|
||||
const pages = await this.pageService.getSidebarPagesBySpaceId(spaceId);
|
||||
|
||||
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[];
|
||||
}
|
||||
}
|
||||
@ -1,25 +1,30 @@
|
||||
import {
|
||||
forwardRef,
|
||||
Inject,
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { CreatePageDto } from '../dto/create-page.dto';
|
||||
import { UpdatePageDto } from '../dto/update-page.dto';
|
||||
import { PageOrderingService } from './page-ordering.service';
|
||||
import { PageWithOrderingDto } from '../dto/page-with-ordering.dto';
|
||||
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 '@docmost/db/pagination/pagination-options';
|
||||
import { PaginationResult } from '@docmost/db/pagination/pagination';
|
||||
import {
|
||||
executeWithPagination,
|
||||
PaginationResult,
|
||||
} from '@docmost/db/pagination/pagination';
|
||||
import { InjectKysely } from 'nestjs-kysely';
|
||||
import { KyselyDB } from '@docmost/db/types/kysely.types';
|
||||
import { generateJitteredKeyBetween } from 'fractional-indexing-jittered';
|
||||
import { MovePageDto } from '../dto/move-page.dto';
|
||||
import { ExpressionBuilder } from 'kysely';
|
||||
import { DB } from '@docmost/db/types/db';
|
||||
import { SidebarPageDto } from '../dto/sidebar-page.dto';
|
||||
|
||||
@Injectable()
|
||||
export class PageService {
|
||||
constructor(
|
||||
private pageRepo: PageRepo,
|
||||
@Inject(forwardRef(() => PageOrderingService))
|
||||
private pageOrderingService: PageOrderingService,
|
||||
@InjectKysely() private readonly db: KyselyDB,
|
||||
) {}
|
||||
|
||||
async findById(
|
||||
@ -27,7 +32,7 @@ export class PageService {
|
||||
includeContent?: boolean,
|
||||
includeYdoc?: boolean,
|
||||
): Promise<Page> {
|
||||
return this.pageRepo.findById(pageId, includeContent, includeYdoc);
|
||||
return this.pageRepo.findById(pageId, { includeContent, includeYdoc });
|
||||
}
|
||||
|
||||
async create(
|
||||
@ -38,33 +43,61 @@ export class PageService {
|
||||
// check if parent page exists
|
||||
if (createPageDto.parentPageId) {
|
||||
// TODO: make sure parent page belongs to same space and user has permissions
|
||||
// make sure user has permission to parent.
|
||||
const parentPage = await this.pageRepo.findById(
|
||||
createPageDto.parentPageId,
|
||||
);
|
||||
if (!parentPage) throw new NotFoundException('Parent page not found');
|
||||
}
|
||||
|
||||
let pageId = undefined;
|
||||
if (createPageDto.pageId) {
|
||||
pageId = createPageDto.pageId;
|
||||
delete createPageDto.pageId;
|
||||
let pagePosition: string;
|
||||
|
||||
const lastPageQuery = this.db
|
||||
.selectFrom('pages')
|
||||
.select(['id', 'position'])
|
||||
.where('spaceId', '=', createPageDto.spaceId)
|
||||
.orderBy('position', 'desc')
|
||||
.limit(1);
|
||||
|
||||
// todo: simplify code
|
||||
if (createPageDto.parentPageId) {
|
||||
// check for children of this page
|
||||
const lastPage = await lastPageQuery
|
||||
.where('parentPageId', '=', createPageDto.parentPageId)
|
||||
.executeTakeFirst();
|
||||
|
||||
if (!lastPage) {
|
||||
pagePosition = generateJitteredKeyBetween(null, null);
|
||||
} else {
|
||||
// if there is an existing page, we should get a position below it
|
||||
pagePosition = generateJitteredKeyBetween(lastPage.position, null);
|
||||
}
|
||||
} else {
|
||||
// for root page
|
||||
const lastPage = await lastPageQuery
|
||||
.where('parentPageId', 'is', null)
|
||||
.executeTakeFirst();
|
||||
|
||||
// if no existing page, make this the first
|
||||
if (!lastPage) {
|
||||
pagePosition = generateJitteredKeyBetween(null, null); // we expect "a0"
|
||||
} else {
|
||||
// if there is an existing page, we should get a position below it
|
||||
pagePosition = generateJitteredKeyBetween(lastPage.position, null);
|
||||
}
|
||||
}
|
||||
|
||||
//TODO: should be in a transaction
|
||||
const createdPage = await this.pageRepo.insertPage({
|
||||
...createPageDto,
|
||||
id: pageId,
|
||||
title: createPageDto.title,
|
||||
position: pagePosition,
|
||||
icon: createPageDto.icon,
|
||||
parentPageId: createPageDto.parentPageId,
|
||||
spaceId: createPageDto.spaceId,
|
||||
creatorId: userId,
|
||||
workspaceId: workspaceId,
|
||||
lastUpdatedById: userId,
|
||||
});
|
||||
|
||||
await this.pageOrderingService.addPageToOrder(
|
||||
createPageDto.spaceId,
|
||||
pageId,
|
||||
createPageDto.parentPageId,
|
||||
);
|
||||
|
||||
return createdPage;
|
||||
}
|
||||
|
||||
@ -103,12 +136,90 @@ export class PageService {
|
||||
);
|
||||
}
|
||||
|
||||
async getSidebarPagesBySpaceId(
|
||||
spaceId: string,
|
||||
limit = 200,
|
||||
): Promise<PageWithOrderingDto[]> {
|
||||
const pages = await this.pageRepo.getSpaceSidebarPages(spaceId, limit);
|
||||
return transformPageResult(pages);
|
||||
withHasChildren(eb: ExpressionBuilder<DB, 'pages'>) {
|
||||
return eb
|
||||
.selectFrom('pages as child')
|
||||
.select((eb) =>
|
||||
eb
|
||||
.case()
|
||||
.when(eb.fn.countAll(), '>', 0)
|
||||
.then(true)
|
||||
.else(false)
|
||||
.end()
|
||||
.as('count'),
|
||||
)
|
||||
.whereRef('child.parentPageId', '=', 'pages.id')
|
||||
.limit(1)
|
||||
.as('hasChildren');
|
||||
}
|
||||
|
||||
async getSidebarPages(
|
||||
dto: SidebarPageDto,
|
||||
pagination: PaginationOptions,
|
||||
): Promise<any> {
|
||||
let query = this.db
|
||||
.selectFrom('pages')
|
||||
.select([
|
||||
'id',
|
||||
'title',
|
||||
'icon',
|
||||
'position',
|
||||
'parentPageId',
|
||||
'spaceId',
|
||||
'creatorId',
|
||||
])
|
||||
.select((eb) => this.withHasChildren(eb))
|
||||
.orderBy('position', 'asc')
|
||||
.where('spaceId', '=', dto.spaceId);
|
||||
|
||||
if (dto.pageId) {
|
||||
query = query.where('parentPageId', '=', dto.pageId);
|
||||
} else {
|
||||
query = query.where('parentPageId', 'is', null);
|
||||
}
|
||||
|
||||
const result = executeWithPagination(query, {
|
||||
page: pagination.page,
|
||||
perPage: 250,
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async movePage(dto: MovePageDto) {
|
||||
// validate position value by attempting to generate a key
|
||||
try {
|
||||
generateJitteredKeyBetween(dto.position, null);
|
||||
} catch (err) {
|
||||
throw new BadRequestException('Invalid move position');
|
||||
}
|
||||
|
||||
const movedPage = await this.pageRepo.findById(dto.pageId);
|
||||
if (!movedPage) throw new NotFoundException('Moved page not found');
|
||||
|
||||
let parentPageId: string;
|
||||
if (movedPage.parentPageId === dto.parentPageId) {
|
||||
parentPageId = undefined;
|
||||
} else {
|
||||
// changing the page's parent
|
||||
if (dto.parentPageId) {
|
||||
const parentPage = await this.pageRepo.findById(dto.parentPageId);
|
||||
if (!parentPage) throw new NotFoundException('Parent page not found');
|
||||
}
|
||||
parentPageId = dto.parentPageId;
|
||||
}
|
||||
|
||||
await this.pageRepo.updatePage(
|
||||
{
|
||||
position: dto.position,
|
||||
parentPageId: parentPageId,
|
||||
},
|
||||
dto.pageId,
|
||||
);
|
||||
|
||||
// TODO
|
||||
// check for duplicates?
|
||||
// permissions
|
||||
}
|
||||
|
||||
async getRecentSpacePages(
|
||||
@ -126,8 +237,8 @@ export class PageService {
|
||||
async forceDelete(pageId: string): Promise<void> {
|
||||
await this.pageRepo.deletePage(pageId);
|
||||
}
|
||||
|
||||
/*
|
||||
}
|
||||
/*
|
||||
// TODO: page deletion and restoration
|
||||
async delete(pageId: string): Promise<void> {
|
||||
await this.dataSource.transaction(async (manager: EntityManager) => {
|
||||
@ -217,4 +328,3 @@ export class PageService {
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
@ -12,7 +12,6 @@ import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
|
||||
import { PageRepo } from './repos/page/page.repo';
|
||||
import { CommentRepo } from './repos/comment/comment.repo';
|
||||
import { PageHistoryRepo } from './repos/page/page-history.repo';
|
||||
import { PageOrderingRepo } from './repos/page/page-ordering.repo';
|
||||
import { AttachmentRepo } from './repos/attachment/attachment.repo';
|
||||
|
||||
// https://github.com/brianc/node-postgres/issues/811
|
||||
@ -35,9 +34,9 @@ types.setTypeParser(types.builtins.INT8, (val) => Number(val));
|
||||
if (environmentService.getEnv() !== 'development') return;
|
||||
if (event.level === 'query') {
|
||||
console.log(event.query.sql);
|
||||
if (event.query.parameters.length > 0) {
|
||||
console.log('parameters: ' + event.query.parameters);
|
||||
}
|
||||
//if (event.query.parameters.length > 0) {
|
||||
//console.log('parameters: ' + event.query.parameters);
|
||||
//}
|
||||
console.log('time: ' + event.queryDurationMillis);
|
||||
}
|
||||
},
|
||||
@ -53,7 +52,6 @@ types.setTypeParser(types.builtins.INT8, (val) => Number(val));
|
||||
SpaceMemberRepo,
|
||||
PageRepo,
|
||||
PageHistoryRepo,
|
||||
PageOrderingRepo,
|
||||
CommentRepo,
|
||||
AttachmentRepo,
|
||||
],
|
||||
@ -66,7 +64,6 @@ types.setTypeParser(types.builtins.INT8, (val) => Number(val));
|
||||
SpaceMemberRepo,
|
||||
PageRepo,
|
||||
PageHistoryRepo,
|
||||
PageOrderingRepo,
|
||||
CommentRepo,
|
||||
AttachmentRepo,
|
||||
],
|
||||
|
||||
@ -0,0 +1,12 @@
|
||||
import { type Kysely } from 'kysely';
|
||||
|
||||
export async function up(db: Kysely<any>): Promise<void> {
|
||||
await db.schema
|
||||
.alterTable('pages')
|
||||
.addColumn('position', 'varchar', (col) => col)
|
||||
.execute();
|
||||
}
|
||||
|
||||
export async function down(db: Kysely<any>): Promise<void> {
|
||||
await db.schema.alterTable('pages').dropColumn('position').execute();
|
||||
}
|
||||
@ -23,13 +23,4 @@ export class PaginationOptions {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
query: string;
|
||||
|
||||
get offset(): number {
|
||||
return (this.page - 1) * this.limit;
|
||||
}
|
||||
}
|
||||
|
||||
export enum PaginationSort {
|
||||
ASC = 'asc',
|
||||
DESC = 'desc',
|
||||
}
|
||||
|
||||
@ -20,6 +20,10 @@ export async function executeWithPagination<O, DB, TB extends keyof DB>(
|
||||
experimental_deferredJoinPrimaryKey?: StringReference<DB, TB>;
|
||||
},
|
||||
): Promise<PaginationResult<O>> {
|
||||
if (opts.page < 1) {
|
||||
opts.page = 1;
|
||||
}
|
||||
console.log('perpage', opts.perPage);
|
||||
qb = qb.limit(opts.perPage + 1).offset((opts.page - 1) * opts.perPage);
|
||||
|
||||
const deferredJoinPrimaryKey = opts.experimental_deferredJoinPrimaryKey;
|
||||
|
||||
@ -72,7 +72,7 @@ export class PageHistoryRepo {
|
||||
.orderBy('createdAt', 'desc');
|
||||
|
||||
const result = executeWithPagination(query, {
|
||||
page: pagination.offset,
|
||||
page: pagination.page,
|
||||
perPage: pagination.limit,
|
||||
});
|
||||
|
||||
|
||||
@ -1,8 +0,0 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectKysely } from 'nestjs-kysely';
|
||||
import { KyselyDB } from '../../types/kysely.types';
|
||||
|
||||
@Injectable()
|
||||
export class PageOrderingRepo {
|
||||
constructor(@InjectKysely() private readonly db: KyselyDB) {}
|
||||
}
|
||||
@ -23,6 +23,7 @@ export class PageRepo {
|
||||
'icon',
|
||||
'coverPhoto',
|
||||
'key',
|
||||
'position',
|
||||
'parentPageId',
|
||||
'creatorId',
|
||||
'lastUpdatedById',
|
||||
@ -38,15 +39,17 @@ export class PageRepo {
|
||||
|
||||
async findById(
|
||||
pageId: string,
|
||||
withJsonContent?: boolean,
|
||||
withYdoc?: boolean,
|
||||
opts?: {
|
||||
includeContent?: boolean;
|
||||
includeYdoc?: boolean;
|
||||
},
|
||||
): Promise<Page> {
|
||||
return await this.db
|
||||
.selectFrom('pages')
|
||||
.select(this.baseFields)
|
||||
.where('id', '=', pageId)
|
||||
.$if(withJsonContent, (qb) => qb.select('content'))
|
||||
.$if(withYdoc, (qb) => qb.select('ydoc'))
|
||||
.$if(opts?.includeContent, (qb) => qb.select('content'))
|
||||
.$if(opts?.includeYdoc, (qb) => qb.select('ydoc'))
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
@ -79,7 +82,7 @@ export class PageRepo {
|
||||
return db
|
||||
.insertInto('pages')
|
||||
.values(insertablePage)
|
||||
.returningAll()
|
||||
.returning(this.baseFields)
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
@ -101,26 +104,4 @@ export class PageRepo {
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getSpaceSidebarPages(spaceId: string, limit: number) {
|
||||
const pages = await this.db
|
||||
.selectFrom('pages as page')
|
||||
.leftJoin('pageOrdering as ordering', 'ordering.entityId', 'page.id')
|
||||
.where('page.spaceId', '=', spaceId)
|
||||
.select([
|
||||
'page.id',
|
||||
'page.title',
|
||||
'page.icon',
|
||||
'page.parentPageId',
|
||||
'page.spaceId',
|
||||
'ordering.childrenIds',
|
||||
'page.creatorId',
|
||||
'page.createdAt',
|
||||
])
|
||||
.orderBy('page.updatedAt', 'desc')
|
||||
.limit(limit)
|
||||
.execute();
|
||||
|
||||
return pages;
|
||||
}
|
||||
}
|
||||
|
||||
14
apps/server/src/kysely/types/db.d.ts
vendored
14
apps/server/src/kysely/types/db.d.ts
vendored
@ -91,18 +91,6 @@ export interface PageHistory {
|
||||
workspaceId: string;
|
||||
}
|
||||
|
||||
export interface PageOrdering {
|
||||
childrenIds: string[];
|
||||
createdAt: Generated<Timestamp>;
|
||||
deletedAt: Timestamp | null;
|
||||
entityId: string;
|
||||
entityType: string;
|
||||
id: Generated<string>;
|
||||
spaceId: string;
|
||||
updatedAt: Generated<Timestamp>;
|
||||
workspaceId: string;
|
||||
}
|
||||
|
||||
export interface Pages {
|
||||
content: Json | null;
|
||||
coverPhoto: string | null;
|
||||
@ -118,6 +106,7 @@ export interface Pages {
|
||||
key: string | null;
|
||||
lastUpdatedById: string | null;
|
||||
parentPageId: string | null;
|
||||
position: string | null;
|
||||
publishedAt: Timestamp | null;
|
||||
slug: string | null;
|
||||
spaceId: string;
|
||||
@ -209,7 +198,6 @@ export interface DB {
|
||||
groups: Groups;
|
||||
groupUsers: GroupUsers;
|
||||
pageHistory: PageHistory;
|
||||
pageOrdering: PageOrdering;
|
||||
pages: Pages;
|
||||
spaceMembers: SpaceMembers;
|
||||
spaces: Spaces;
|
||||
|
||||
@ -8,7 +8,6 @@ import {
|
||||
Users,
|
||||
Workspaces,
|
||||
PageHistory as History,
|
||||
PageOrdering as Ordering,
|
||||
GroupUsers,
|
||||
SpaceMembers,
|
||||
WorkspaceInvitations,
|
||||
@ -63,11 +62,6 @@ export type PageHistory = Selectable<History>;
|
||||
export type InsertablePageHistory = Insertable<History>;
|
||||
export type UpdatablePageHistory = Updateable<Omit<History, 'id'>>;
|
||||
|
||||
// PageOrdering
|
||||
export type PageOrdering = Selectable<Ordering>;
|
||||
export type InsertablePageOrdering = Insertable<Ordering>;
|
||||
export type UpdatablePageOrdering = Updateable<Omit<Ordering, 'id'>>;
|
||||
|
||||
// Comment
|
||||
export type Comment = Selectable<Comments>;
|
||||
export type InsertableComment = Insertable<Comments>;
|
||||
|
||||
Reference in New Issue
Block a user