switch to nx monorepo

This commit is contained in:
Philipinho
2024-01-09 18:58:26 +01:00
parent e1bb2632b8
commit 093e634c0b
273 changed files with 11419 additions and 31 deletions

View File

@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

View File

@ -0,0 +1,26 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CoreModule } from './core/core.module';
import { EnvironmentModule } from './environment/environment.module';
import { CollaborationModule } from './collaboration/collaboration.module';
import { DatabaseModule } from './database/database.module';
import { WsModule } from './ws/ws.module';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';
@Module({
imports: [
CoreModule,
EnvironmentModule,
DatabaseModule,
CollaborationModule,
WsModule,
ServeStaticModule.forRoot({
rootPath: join(__dirname, '..', '..', 'client/dist'),
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -0,0 +1,43 @@
import { WebSocketServer } from 'ws';
export class CollabWsAdapter {
private readonly wss: WebSocketServer;
constructor() {
this.wss = new WebSocketServer({ noServer: true });
}
handleUpgrade(path: string, httpServer) {
httpServer.on('upgrade', (request, socket, head) => {
try {
const baseUrl = 'ws://' + request.headers.host + '/';
const pathname = new URL(request.url, baseUrl).pathname;
if (pathname === path) {
this.wss.handleUpgrade(request, socket, head, (ws) => {
this.wss.emit('connection', ws, request);
});
} else if (pathname === '/socket.io/') {
return;
} else {
socket.destroy();
}
} catch (err) {
socket.end('HTTP/1.1 400\r\n' + err.message);
}
});
return this.wss;
}
public destroy() {
try {
this.wss.clients.forEach((client) => {
client.terminate();
});
this.wss.close();
} catch (err) {
console.error(err);
}
}
}

View File

@ -0,0 +1,34 @@
import { Server as HocuspocusServer } from '@hocuspocus/server';
import { IncomingMessage } from 'http';
import WebSocket from 'ws';
import { AuthenticationExtension } from './extensions/authentication.extension';
import { PersistenceExtension } from './extensions/persistence.extension';
import { Injectable } from '@nestjs/common';
import { HistoryExtension } from './extensions/history.extension';
@Injectable()
export class CollaborationGateway {
constructor(
private authenticationExtension: AuthenticationExtension,
private persistenceExtension: PersistenceExtension,
private historyExtension: HistoryExtension,
) {}
private hocuspocus = HocuspocusServer.configure({
debounce: 5000,
maxDebounce: 10000,
extensions: [
this.authenticationExtension,
this.persistenceExtension,
this.historyExtension,
],
});
handleConnection(client: WebSocket, request: IncomingMessage): any {
this.hocuspocus.handleConnection(client, request);
}
destroy() {
this.hocuspocus.destroy();
}
}

View File

@ -0,0 +1,47 @@
import { Module, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { UserModule } from '../core/user/user.module';
import { AuthModule } from '../core/auth/auth.module';
import { AuthenticationExtension } from './extensions/authentication.extension';
import { PersistenceExtension } from './extensions/persistence.extension';
import { PageModule } from '../core/page/page.module';
import { CollaborationGateway } from './collaboration.gateway';
import { HttpAdapterHost } from '@nestjs/core';
import { CollabWsAdapter } from './adapter/collab-ws.adapter';
import { IncomingMessage } from 'http';
import { WebSocket } from 'ws';
import { HistoryExtension } from './extensions/history.extension';
@Module({
providers: [
CollaborationGateway,
AuthenticationExtension,
PersistenceExtension,
HistoryExtension,
],
imports: [UserModule, AuthModule, PageModule],
})
export class CollaborationModule implements OnModuleInit, OnModuleDestroy {
private collabWsAdapter: CollabWsAdapter;
private path = '/collaboration';
constructor(
private readonly collaborationGateway: CollaborationGateway,
private readonly httpAdapterHost: HttpAdapterHost,
) {}
onModuleInit() {
this.collabWsAdapter = new CollabWsAdapter();
const httpServer = this.httpAdapterHost.httpAdapter.getHttpServer();
const wss = this.collabWsAdapter.handleUpgrade(this.path, httpServer);
wss.on('connection', (client: WebSocket, request: IncomingMessage) => {
this.collaborationGateway.handleConnection(client, request);
});
}
onModuleDestroy(): any {
this.collaborationGateway.destroy();
this.collabWsAdapter.destroy();
}
}

View File

@ -0,0 +1,34 @@
import { Extension, onAuthenticatePayload } from '@hocuspocus/server';
import { UserService } from '../../core/user/user.service';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { TokenService } from '../../core/auth/services/token.service';
@Injectable()
export class AuthenticationExtension implements Extension {
constructor(
private tokenService: TokenService,
private userService: UserService,
) {}
async onAuthenticate(data: onAuthenticatePayload) {
const { documentName, token } = data;
let jwtPayload = null;
try {
jwtPayload = await this.tokenService.verifyJwt(token);
} catch (error) {
throw new UnauthorizedException('Could not verify jwt token');
}
const userId = jwtPayload.sub;
const user = await this.userService.findById(userId);
//TODO: Check if the page exists and verify user permissions for page.
// if all fails, abort connection
return {
user,
};
}
}

View File

@ -0,0 +1,64 @@
import {
Extension,
onChangePayload,
onDisconnectPayload,
} from '@hocuspocus/server';
import { Injectable } from '@nestjs/common';
import { PageService } from '../../core/page/services/page.service';
import { PageHistoryService } from '../../core/page/services/page-history.service';
@Injectable()
export class HistoryExtension implements Extension {
ACTIVE_EDITING_INTERVAL = 10 * 60 * 1000; // 10 minutes
historyIntervalMap = new Map<string, NodeJS.Timeout>();
lastEditTimeMap = new Map<string, number>();
constructor(
private readonly pageService: PageService,
private readonly pageHistoryService: PageHistoryService,
) {}
async onChange(data: onChangePayload): Promise<void> {
const pageId = data.documentName;
this.lastEditTimeMap.set(pageId, Date.now());
if (!this.historyIntervalMap.has(pageId)) {
const historyInterval = setInterval(() => {
if (this.isActiveEditing(pageId)) {
this.recordHistory(pageId);
}
}, this.ACTIVE_EDITING_INTERVAL);
this.historyIntervalMap.set(pageId, historyInterval);
}
}
async onDisconnect(data: onDisconnectPayload): Promise<void> {
const pageId = data.documentName;
if (data.clientsCount === 0) {
if (this.historyIntervalMap.has(pageId)) {
clearInterval(this.historyIntervalMap.get(pageId));
this.historyIntervalMap.delete(pageId);
this.lastEditTimeMap.delete(pageId);
}
}
}
isActiveEditing(pageId: string): boolean {
const lastEditTime = this.lastEditTimeMap.get(pageId);
if (!lastEditTime) {
return false;
}
return Date.now() - lastEditTime < this.ACTIVE_EDITING_INTERVAL;
}
async recordHistory(pageId: string) {
try {
const page = await this.pageService.findWithContent(pageId);
// Todo: compare if data is the same as the previous version
await this.pageHistoryService.saveHistory(page);
console.log(`New history created for: ${pageId}`);
} catch (err) {
console.error('An error occurred saving page history', err);
}
}
}

View File

@ -0,0 +1,68 @@
import {
Extension,
onLoadDocumentPayload,
onStoreDocumentPayload,
} from '@hocuspocus/server';
import * as Y from 'yjs';
import { PageService } from '../../core/page/services/page.service';
import { Injectable } from '@nestjs/common';
import { TiptapTransformer } from '@hocuspocus/transformer';
@Injectable()
export class PersistenceExtension implements Extension {
constructor(private readonly pageService: PageService) {}
async onLoadDocument(data: onLoadDocumentPayload) {
const { documentName, document } = data;
const pageId = documentName;
if (!document.isEmpty('default')) {
return;
}
const page = await this.pageService.findWithAllFields(pageId);
if (!page) {
console.log('page does not exist.');
//TODO: terminate connection if the page does not exist?
return;
}
if (page.ydoc) {
console.log('ydoc loaded from db');
const doc = new Y.Doc();
const dbState = new Uint8Array(page.ydoc);
Y.applyUpdate(doc, dbState);
return doc;
}
// if no ydoc state in db convert json in page.content to Ydoc.
if (page.content) {
console.log('converting json to ydoc');
const ydoc = TiptapTransformer.toYdoc(page.content, 'default');
Y.encodeStateAsUpdate(ydoc);
return ydoc;
}
console.log('creating fresh ydoc');
return new Y.Doc();
}
async onStoreDocument(data: onStoreDocumentPayload) {
const { documentName, document, context } = data;
const pageId = documentName;
const tiptapJson = TiptapTransformer.fromYdoc(document, 'default');
const ydocState = Buffer.from(Y.encodeStateAsUpdate(document));
try {
await this.pageService.updateState(pageId, tiptapJson, ydocState);
} catch (err) {
console.error(`Failed to update page ${documentName}`);
}
}
}

View File

@ -0,0 +1,110 @@
import {
BadRequestException,
Controller,
HttpCode,
HttpStatus,
Post,
Req,
Res,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { AttachmentService } from './attachment.service';
import { FastifyReply, FastifyRequest } from 'fastify';
import { AttachmentInterceptor } from './attachment.interceptor';
import { JwtUser } from '../../decorators/jwt-user.decorator';
import { JwtGuard } from '../auth/guards/JwtGuard';
import * as bytes from 'bytes';
@Controller('attachments')
export class AttachmentController {
constructor(private readonly attachmentService: AttachmentService) {}
@UseGuards(JwtGuard)
@HttpCode(HttpStatus.CREATED)
@Post('upload/avatar')
@UseInterceptors(AttachmentInterceptor)
async uploadAvatar(
@JwtUser() jwtUser,
@Req() req: FastifyRequest,
@Res() res: FastifyReply,
) {
const maxFileSize = bytes('5MB');
try {
const file = req.file({
limits: { fileSize: maxFileSize, fields: 1, files: 1 },
});
const fileResponse = await this.attachmentService.uploadAvatar(
file,
jwtUser.id,
);
return res.send(fileResponse);
} catch (err) {
throw new BadRequestException('Error processing file upload.');
}
}
@UseGuards(JwtGuard)
@HttpCode(HttpStatus.CREATED)
@Post('upload/workspace-logo')
@UseInterceptors(AttachmentInterceptor)
async uploadWorkspaceLogo(
@JwtUser() jwtUser,
@Req() req: FastifyRequest,
@Res() res: FastifyReply,
) {
const maxFileSize = bytes('5MB');
try {
const file = req.file({
limits: { fileSize: maxFileSize, fields: 1, files: 1 },
});
// TODO FIX
const workspaceId = '123';
const fileResponse = await this.attachmentService.uploadWorkspaceLogo(
file,
workspaceId,
jwtUser.id,
);
return res.send(fileResponse);
} catch (err) {
throw new BadRequestException('Error processing file upload.');
}
}
@UseGuards(JwtGuard)
@HttpCode(HttpStatus.CREATED)
@Post('upload/file')
@UseInterceptors(AttachmentInterceptor)
async uploadFile(
@JwtUser() jwtUser,
@Req() req: FastifyRequest,
@Res() res: FastifyReply,
) {
const maxFileSize = bytes('20MB');
try {
const file = req.file({
limits: { fileSize: maxFileSize, fields: 1, files: 1 },
});
const workspaceId = '123';
const fileResponse = await this.attachmentService.uploadWorkspaceLogo(
file,
workspaceId,
jwtUser.id,
);
return res.send(fileResponse);
} catch (err) {
throw new BadRequestException('Error processing file upload.');
}
}
}

View File

@ -0,0 +1,25 @@
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
BadRequestException,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { FastifyRequest } from 'fastify';
@Injectable()
export class AttachmentInterceptor implements NestInterceptor {
public intercept(
context: ExecutionContext,
next: CallHandler,
): Observable<any> {
const req: FastifyRequest = context.switchToHttp().getRequest();
if (!req.isMultipart() || !req.file) {
throw new BadRequestException('Invalid multipart content type');
}
return next.handle();
}
}

View File

@ -0,0 +1,23 @@
import { Module } from '@nestjs/common';
import { AttachmentService } from './attachment.service';
import { AttachmentController } from './attachment.controller';
import { StorageModule } from '../storage/storage.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Attachment } from './entities/attachment.entity';
import { AttachmentRepository } from './repositories/attachment.repository';
import { AuthModule } from '../auth/auth.module';
import { UserModule } from '../user/user.module';
import { WorkspaceModule } from '../workspace/workspace.module';
@Module({
imports: [
TypeOrmModule.forFeature([Attachment]),
StorageModule,
AuthModule,
UserModule,
WorkspaceModule,
],
controllers: [AttachmentController],
providers: [AttachmentService, AttachmentRepository],
})
export class AttachmentModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AttachmentService } from './attachment.service';
describe('AttachmentService', () => {
let service: AttachmentService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AttachmentService],
}).compile();
service = module.get<AttachmentService>(AttachmentService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,164 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { StorageService } from '../storage/storage.service';
import { MultipartFile } from '@fastify/multipart';
import { AttachmentRepository } from './repositories/attachment.repository';
import { Attachment } from './entities/attachment.entity';
import { UserService } from '../user/user.service';
import { UpdateUserDto } from '../user/dto/update-user.dto';
import {
AttachmentType,
getAttachmentPath,
PreparedFile,
prepareFile,
validateFileType,
} from './attachment.utils';
import { v4 as uuid4 } from 'uuid';
import { WorkspaceService } from '../workspace/services/workspace.service';
import { UpdateWorkspaceDto } from '../workspace/dto/update-workspace.dto';
@Injectable()
export class AttachmentService {
constructor(
private readonly storageService: StorageService,
private readonly attachmentRepo: AttachmentRepository,
private readonly workspaceService: WorkspaceService,
private readonly userService: UserService,
) {}
async uploadToDrive(preparedFile: PreparedFile, filePath: string) {
try {
await this.storageService.upload(filePath, preparedFile.buffer);
} catch (err) {
console.error('Error uploading file to drive:', err);
throw new BadRequestException('Error uploading file to drive');
}
}
async updateUserAvatar(userId: string, avatarUrl: string) {
const updateUserDto = new UpdateUserDto();
updateUserDto.avatarUrl = avatarUrl;
await this.userService.update(userId, updateUserDto);
}
async updateWorkspaceLogo(workspaceId: string, logoUrl: string) {
const updateWorkspaceDto = new UpdateWorkspaceDto();
updateWorkspaceDto.logo = logoUrl;
await this.workspaceService.update(workspaceId, updateWorkspaceDto);
}
async uploadAvatar(filePromise: Promise<MultipartFile>, userId: string) {
try {
const preparedFile: PreparedFile = await prepareFile(filePromise);
const allowedImageTypes = ['.jpg', '.jpeg', '.png'];
validateFileType(preparedFile.fileExtension, allowedImageTypes);
preparedFile.fileName = uuid4() + preparedFile.fileExtension;
const attachmentPath = getAttachmentPath(AttachmentType.Avatar);
const filePath = `${attachmentPath}/${preparedFile.fileName}`;
await this.uploadToDrive(preparedFile, filePath);
const attachment = new Attachment();
attachment.creatorId = userId;
attachment.pageId = null;
attachment.workspaceId = null;
attachment.type = AttachmentType.Avatar;
attachment.filePath = filePath;
attachment.fileName = preparedFile.fileName;
attachment.fileSize = preparedFile.fileSize;
attachment.mimeType = preparedFile.mimeType;
attachment.fileExt = preparedFile.fileExtension;
await this.updateUserAvatar(userId, filePath);
return attachment;
} catch (err) {
console.log(err);
throw new BadRequestException(err.message);
}
}
async uploadWorkspaceLogo(
filePromise: Promise<MultipartFile>,
workspaceId: string,
userId: string,
) {
try {
const preparedFile: PreparedFile = await prepareFile(filePromise);
const allowedImageTypes = ['.jpg', '.jpeg', '.png'];
validateFileType(preparedFile.fileExtension, allowedImageTypes);
preparedFile.fileName = uuid4() + preparedFile.fileExtension;
const attachmentPath = getAttachmentPath(
AttachmentType.WorkspaceLogo,
workspaceId,
);
const filePath = `${attachmentPath}/${preparedFile.fileName}`;
await this.uploadToDrive(preparedFile, filePath);
const attachment = new Attachment();
attachment.creatorId = userId;
attachment.pageId = null;
attachment.workspaceId = workspaceId;
attachment.type = AttachmentType.WorkspaceLogo;
attachment.filePath = filePath;
attachment.fileName = preparedFile.fileName;
attachment.fileSize = preparedFile.fileSize;
attachment.mimeType = preparedFile.mimeType;
attachment.fileExt = preparedFile.fileExtension;
await this.updateWorkspaceLogo(workspaceId, filePath);
return attachment;
} catch (err) {
console.log(err);
throw new BadRequestException(err.message);
}
}
async uploadFile(
filePromise: Promise<MultipartFile>,
pageId: string,
workspaceId: string,
userId: string,
) {
try {
const preparedFile: PreparedFile = await prepareFile(filePromise);
const allowedImageTypes = ['.jpg', '.jpeg', '.png', '.pdf'];
validateFileType(preparedFile.fileExtension, allowedImageTypes);
const attachmentPath = getAttachmentPath(
AttachmentType.WorkspaceLogo,
workspaceId,
);
const filePath = `${attachmentPath}/${preparedFile.fileName}`;
await this.uploadToDrive(preparedFile, filePath);
const attachment = new Attachment();
attachment.creatorId = userId;
attachment.pageId = pageId;
attachment.workspaceId = workspaceId;
attachment.type = AttachmentType.WorkspaceLogo;
attachment.filePath = filePath;
attachment.fileName = preparedFile.fileName;
attachment.fileSize = preparedFile.fileSize;
attachment.mimeType = preparedFile.mimeType;
attachment.fileExt = preparedFile.fileExtension;
return attachment;
} catch (err) {
console.log(err);
throw new BadRequestException(err.message);
}
}
}

View File

@ -0,0 +1,75 @@
import { MultipartFile } from '@fastify/multipart';
import { randomBytes } from 'crypto';
import { sanitize } from 'sanitize-filename-ts';
import * as path from 'path';
export interface PreparedFile {
buffer: Buffer;
fileName: string;
fileSize: number;
fileExtension: string;
mimeType: string;
}
export async function prepareFile(
filePromise: Promise<MultipartFile>,
): Promise<PreparedFile> {
try {
const rand = randomBytes(4).toString('hex');
const file = await filePromise;
if (!file) {
throw new Error('No file provided');
}
const buffer = await file.toBuffer();
const sanitizedFilename = sanitize(file.filename).replace(/ /g, '_');
const fileName = `${rand}_${sanitizedFilename}`;
const fileSize = buffer.length;
const fileExtension = path.extname(file.filename).toLowerCase();
return {
buffer,
fileName,
fileSize,
fileExtension,
mimeType: file.mimetype,
};
} catch (error) {
console.error('Error in file preparation:', error);
throw error;
}
}
export function validateFileType(
fileExtension: string,
allowedTypes: string[],
) {
if (!allowedTypes.includes(fileExtension)) {
throw new Error('Invalid file type');
}
}
export enum AttachmentType {
Avatar = 'Avatar',
WorkspaceLogo = 'WorkspaceLogo',
File = 'file',
}
export function getAttachmentPath(
type: AttachmentType,
workspaceId?: string,
): string {
if (!workspaceId && type != AttachmentType.Avatar) {
throw new Error('Workspace ID is required for this attachment type');
}
switch (type) {
case AttachmentType.Avatar:
return 'avatars';
case AttachmentType.WorkspaceLogo:
return `${workspaceId}/logo`;
default:
return `${workspaceId}/files`;
}
}

View File

@ -0,0 +1,5 @@
import { IsOptional, IsString, IsUUID } from 'class-validator';
export class AvatarUploadDto {
}

View File

@ -0,0 +1,65 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
CreateDateColumn,
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('attachments')
export class Attachment {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 255 })
fileName: string;
@Column({ type: 'varchar' })
filePath: string;
@Column({ type: 'bigint' })
fileSize: number;
@Column({ type: 'varchar', length: 55 })
fileExt: string;
@Column({ type: 'varchar', length: 255 })
mimeType: string;
@Column({ type: 'varchar', length: 55 })
type: string; // e.g. page / workspace / avatar
@Column()
creatorId: string;
@ManyToOne(() => User)
@JoinColumn({ name: 'creatorId' })
creator: User;
@Column({ nullable: true })
pageId: string;
@ManyToOne(() => Page)
@JoinColumn({ name: 'pageId' })
page: Page;
@Column({ nullable: true })
workspaceId: string;
@ManyToOne(() => Workspace, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'workspaceId' })
workspace: Workspace;
@CreateDateColumn()
createdAt: Date;
@DeleteDateColumn({ nullable: true })
deletedAt: Date;
}

View File

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

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthController } from './auth.controller';
describe('AuthController', () => {
let controller: AuthController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
}).compile();
controller = module.get<AuthController>(AuthController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,27 @@
import {
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Post,
} from '@nestjs/common';
import { LoginDto } from './dto/login.dto';
import { AuthService } from './services/auth.service';
import { CreateUserDto } from '../user/dto/create-user.dto';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@HttpCode(HttpStatus.OK)
@Post('login')
async login(@Body() loginInput: LoginDto) {
return await this.authService.login(loginInput);
}
@HttpCode(HttpStatus.OK)
@Post('register')
async register(@Body() createUserDto: CreateUserDto) {
return await this.authService.register(createUserDto);
}
}

View File

@ -0,0 +1,29 @@
import { forwardRef, Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './services/auth.service';
import { JwtModule } from '@nestjs/jwt';
import { EnvironmentService } from '../../environment/environment.service';
import { TokenService } from './services/token.service';
import { UserModule } from '../user/user.module';
@Module({
imports: [
JwtModule.registerAsync({
useFactory: async (environmentService: EnvironmentService) => {
return {
global: true,
secret: environmentService.getJwtSecret(),
signOptions: {
expiresIn: environmentService.getJwtTokenExpiresIn(),
},
};
},
inject: [EnvironmentService],
}),
forwardRef(() => UserModule),
],
controllers: [AuthController],
providers: [AuthService, TokenService],
exports: [TokenService],
})
export class AuthModule {}

View File

@ -0,0 +1,11 @@
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class LoginDto {
@IsNotEmpty()
@IsEmail()
email: string;
@IsNotEmpty()
@IsString()
password: string;
}

View File

@ -0,0 +1,4 @@
export interface TokensDto {
accessToken: string;
refreshToken: string;
}

View File

@ -0,0 +1,30 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { TokenService } from '../services/token.service';
@Injectable()
export class JwtGuard implements CanActivate {
constructor(private tokenService: TokenService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token: string = await this.tokenService.extractTokenFromHeader(
request,
);
if (!token) {
throw new UnauthorizedException('Invalid jwt token');
}
try {
request['user'] = await this.tokenService.verifyJwt(token);
} catch (error) {
throw new UnauthorizedException('Could not verify jwt token');
}
return true;
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();
service = module.get<AuthService>(AuthService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,41 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { LoginDto } from '../dto/login.dto';
import { User } from '../../user/entities/user.entity';
import { CreateUserDto } from '../../user/dto/create-user.dto';
import { UserService } from '../../user/user.service';
import { TokenService } from './token.service';
import { TokensDto } from '../dto/tokens.dto';
@Injectable()
export class AuthService {
constructor(
private userService: UserService,
private tokenService: TokenService,
) {}
async login(loginDto: LoginDto) {
const user: User = await this.userService.findByEmail(loginDto.email);
const invalidCredentialsMessage = 'email or password does not match';
if (
!user ||
!(await this.userService.compareHash(loginDto.password, user.password))
) {
throw new UnauthorizedException(invalidCredentialsMessage);
}
user.lastLoginAt = new Date();
const tokens: TokensDto = await this.tokenService.generateTokens(user);
return { tokens };
}
async register(createUserDto: CreateUserDto) {
const user: User = await this.userService.create(createUserDto);
const tokens: TokensDto = await this.tokenService.generateTokens(user);
return { tokens };
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { TokenService } from './token.service';
describe('TokenService', () => {
let service: TokenService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [TokenService],
}).compile();
service = module.get<TokenService>(TokenService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,43 @@
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { EnvironmentService } from '../../../environment/environment.service';
import { User } from '../../user/entities/user.entity';
import { FastifyRequest } from 'fastify';
import { TokensDto } from '../dto/tokens.dto';
export type JwtPayload = { sub: string; email: string };
@Injectable()
export class TokenService {
constructor(
private jwtService: JwtService,
private environmentService: EnvironmentService,
) {}
async generateJwt(user: User): Promise<string> {
const payload: JwtPayload = {
sub: user.id,
email: user.email,
};
return await this.jwtService.signAsync(payload);
}
async generateTokens(user: User): Promise<TokensDto> {
return {
accessToken: await this.generateJwt(user),
refreshToken: null,
};
}
async verifyJwt(token: string) {
return await this.jwtService.verifyAsync(token, {
secret: this.environmentService.getJwtSecret(),
});
}
async extractTokenFromHeader(
request: FastifyRequest,
): Promise<string | undefined> {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}

View File

@ -0,0 +1,75 @@
import {
Controller,
Post,
Body,
HttpCode,
HttpStatus,
Req,
UseGuards,
} from '@nestjs/common';
import { CommentService } from './comment.service';
import { CreateCommentDto } from './dto/create-comment.dto';
import { UpdateCommentDto } from './dto/update-comment.dto';
import { FastifyRequest } from 'fastify';
import { JwtGuard } from '../auth/guards/JwtGuard';
import { CommentsInput, SingleCommentInput } from './dto/comments.input';
import { ResolveCommentDto } from './dto/resolve-comment.dto';
import { WorkspaceService } from '../workspace/services/workspace.service';
@UseGuards(JwtGuard)
@Controller('comments')
export class CommentController {
constructor(
private readonly commentService: CommentService,
private readonly workspaceService: WorkspaceService,
) {}
@HttpCode(HttpStatus.CREATED)
@Post('create')
async create(
@Req() req: FastifyRequest,
@Body() createCommentDto: CreateCommentDto,
) {
const jwtPayload = req['user'];
const userId = jwtPayload.sub;
const workspaceId = (
await this.workspaceService.getUserCurrentWorkspace(jwtPayload.sub)
).id;
return this.commentService.create(userId, workspaceId, createCommentDto);
}
@HttpCode(HttpStatus.OK)
@Post()
findPageComments(@Body() input: CommentsInput) {
return this.commentService.findByPageId(input.pageId);
}
@HttpCode(HttpStatus.OK)
@Post('view')
findOne(@Body() input: SingleCommentInput) {
return this.commentService.findWithCreator(input.id);
}
@HttpCode(HttpStatus.OK)
@Post('update')
update(@Body() updateCommentDto: UpdateCommentDto) {
return this.commentService.update(updateCommentDto.id, updateCommentDto);
}
@HttpCode(HttpStatus.OK)
@Post('resolve')
resolve(
@Req() req: FastifyRequest,
@Body() resolveCommentDto: ResolveCommentDto,
) {
const userId = req['user'].sub;
return this.commentService.resolveComment(userId, resolveCommentDto);
}
@HttpCode(HttpStatus.OK)
@Post('delete')
remove(@Body() input: SingleCommentInput) {
return this.commentService.remove(input.id);
}
}

View File

@ -0,0 +1,22 @@
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 { AuthModule } from '../auth/auth.module';
import { WorkspaceModule } from '../workspace/workspace.module';
import { Comment } from './entities/comment.entity';
import { PageModule } from '../page/page.module';
@Module({
imports: [
TypeOrmModule.forFeature([Comment]),
AuthModule,
WorkspaceModule,
PageModule,
],
controllers: [CommentController],
providers: [CommentService, CommentRepository],
exports: [CommentService, CommentRepository],
})
export class CommentModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CommentService } from './comment.service';
describe('CommentService', () => {
let service: CommentService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CommentService],
}).compile();
service = module.get<CommentService>(CommentService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,122 @@
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';
@Injectable()
export class CommentService {
constructor(
private commentRepository: CommentRepository,
private pageService: PageService,
) {}
async findWithCreator(commentId: string) {
return await this.commentRepository.findOne({
where: { id: commentId },
relations: ['creator'],
});
}
async create(
userId: string,
workspaceId: string,
createCommentDto: CreateCommentDto,
) {
const comment = plainToInstance(Comment, createCommentDto);
comment.creatorId = userId;
comment.workspaceId = workspaceId;
comment.content = JSON.parse(createCommentDto.content);
if (createCommentDto.selection) {
comment.selection = createCommentDto.selection.substring(0, 250);
}
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'],
});
if (!parentComment) {
throw new BadRequestException('Parent comment not found');
}
if (parentComment.parentCommentId !== null) {
throw new BadRequestException('You cannot reply to a reply');
}
}
const savedComment = await this.commentRepository.save(comment);
return this.findWithCreator(savedComment.id);
}
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 update(
commentId: string,
updateCommentDto: UpdateCommentDto,
): Promise<Comment> {
updateCommentDto.content = 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,
{
resolvedAt,
resolvedById,
},
);
if (result.affected === 0) {
throw new BadRequestException(`Comment not found`);
}
return this.findWithCreator(resolveCommentDto.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.`);
}
}
}

View File

@ -0,0 +1,11 @@
import { IsUUID } from 'class-validator';
export class CommentsInput {
@IsUUID()
pageId: string;
}
export class SingleCommentInput {
@IsUUID()
id: string;
}

View File

@ -0,0 +1,21 @@
import { IsJSON, IsOptional, IsString, IsUUID } from 'class-validator';
export class CreateCommentDto {
@IsOptional()
@IsUUID()
id?: string;
@IsUUID()
pageId: string;
@IsJSON()
content: any;
@IsOptional()
@IsString()
selection: string;
@IsOptional()
@IsUUID()
parentCommentId: string;
}

View File

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

View File

@ -0,0 +1,9 @@
import { IsJSON, IsUUID } from 'class-validator';
export class UpdateCommentDto {
@IsUUID()
id: string;
@IsJSON()
content: any;
}

View File

@ -0,0 +1,82 @@
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

@ -0,0 +1,14 @@
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 });
}
}

View File

@ -0,0 +1,24 @@
import { Module } from '@nestjs/common';
import { UserModule } from './user/user.module';
import { AuthModule } from './auth/auth.module';
import { WorkspaceModule } from './workspace/workspace.module';
import { PageModule } from './page/page.module';
import { StorageModule } from './storage/storage.module';
import { AttachmentModule } from './attachment/attachment.module';
import { EnvironmentModule } from '../environment/environment.module';
import { CommentModule } from './comment/comment.module';
@Module({
imports: [
UserModule,
AuthModule,
WorkspaceModule,
PageModule,
StorageModule.forRootAsync({
imports: [EnvironmentModule],
}),
AttachmentModule,
CommentModule,
],
})
export class CoreModule {}

View File

@ -0,0 +1,15 @@
import { IsOptional, IsString, IsUUID } from 'class-validator';
export class CreatePageDto {
@IsOptional()
@IsUUID()
id?: string;
@IsOptional()
@IsString()
title?: string;
@IsOptional()
@IsString()
parentPageId?: string;
}

View File

@ -0,0 +1,6 @@
import { IsUUID } from 'class-validator';
export class DeletePageDto {
@IsUUID()
id: string;
}

View File

@ -0,0 +1,6 @@
import { IsUUID } from 'class-validator';
export class HistoryDetailsDto {
@IsUUID()
id: string;
}

View File

@ -0,0 +1,18 @@
import { IsString, IsOptional, IsUUID } from 'class-validator';
export class MovePageDto {
@IsUUID()
id: string;
@IsOptional()
@IsString()
after?: string;
@IsOptional()
@IsString()
before?: string;
@IsOptional()
@IsString()
parentId?: string | null;
}

View File

@ -0,0 +1,6 @@
import { IsUUID } from 'class-validator';
export class PageDetailsDto {
@IsUUID()
id: string;
}

View File

@ -0,0 +1,6 @@
import { IsUUID } from 'class-validator';
export class PageHistoryDto {
@IsUUID()
pageId: string;
}

View File

@ -0,0 +1,5 @@
import { Page } from '../entities/page.entity';
export class PageWithOrderingDto extends Page {
childrenIds?: string[];
}

View File

@ -0,0 +1,8 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreatePageDto } from './create-page.dto';
import { IsUUID } from 'class-validator';
export class UpdatePageDto extends PartialType(CreatePageDto) {
@IsUUID()
id: string;
}

View File

@ -0,0 +1,63 @@
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';
@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()
workspaceId: string;
@ManyToOne(() => Workspace, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'workspaceId' })
workspace: Workspace;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}

View File

@ -0,0 +1,46 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
Unique,
CreateDateColumn,
UpdateDateColumn,
DeleteDateColumn,
} from 'typeorm';
import { Workspace } from '../../workspace/entities/workspace.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 })
childrenIds: string[];
@ManyToOne(() => Workspace, (workspace) => workspace.id, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'workspaceId' })
workspace: Workspace;
@Column('uuid')
workspaceId: string;
@DeleteDateColumn({ nullable: true })
deletedAt: Date;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}

View File

@ -0,0 +1,110 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
OneToMany,
DeleteDateColumn,
} 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';
@Entity('pages')
export class Page {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ length: 500, nullable: true })
title: string;
@Column({ type: 'jsonb', nullable: true })
content: string;
@Column({ type: 'text', nullable: true })
html: string;
@Column({ type: 'bytea', nullable: true })
ydoc: any;
@Column({ nullable: true })
slug: string;
@Column({ nullable: true })
icon: 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()
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

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PageController } from './page.controller';
import { PageService } from './services/page.service';
describe('PageController', () => {
let controller: PageController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [PageController],
providers: [PageService],
}).compile();
controller = module.get<PageController>(PageController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,120 @@
import {
Controller,
Post,
Body,
HttpCode,
HttpStatus,
UseGuards,
} from '@nestjs/common';
import { PageService } from './services/page.service';
import { CreatePageDto } from './dto/create-page.dto';
import { UpdatePageDto } from './dto/update-page.dto';
import { JwtGuard } from '../auth/guards/JwtGuard';
import { WorkspaceService } from '../workspace/services/workspace.service';
import { MovePageDto } from './dto/move-page.dto';
import { PageDetailsDto } from './dto/page-details.dto';
import { DeletePageDto } from './dto/delete-page.dto';
import { PageOrderingService } from './services/page-ordering.service';
import { PageHistoryService } from './services/page-history.service';
import { HistoryDetailsDto } from './dto/history-details.dto';
import { PageHistoryDto } from './dto/page-history.dto';
import { JwtUser } from '../../decorators/jwt-user.decorator';
@UseGuards(JwtGuard)
@Controller('pages')
export class PageController {
constructor(
private readonly pageService: PageService,
private readonly pageOrderService: PageOrderingService,
private readonly pageHistoryService: PageHistoryService,
private readonly workspaceService: WorkspaceService,
) {}
@HttpCode(HttpStatus.OK)
@Post('/details')
async getPage(@Body() input: PageDetailsDto) {
return this.pageService.findOne(input.id);
}
@HttpCode(HttpStatus.CREATED)
@Post('create')
async create(@JwtUser() jwtUser, @Body() createPageDto: CreatePageDto) {
const workspaceId = (
await this.workspaceService.getUserCurrentWorkspace(jwtUser.id)
).id;
return this.pageService.create(jwtUser.id, workspaceId, createPageDto);
}
@HttpCode(HttpStatus.OK)
@Post('update')
async update(@JwtUser() jwtUser, @Body() updatePageDto: UpdatePageDto) {
return this.pageService.update(updatePageDto.id, updatePageDto, jwtUser.id);
}
@HttpCode(HttpStatus.OK)
@Post('delete')
async delete(@Body() deletePageDto: DeletePageDto) {
await this.pageService.delete(deletePageDto.id);
}
@HttpCode(HttpStatus.OK)
@Post('restore')
async restore(@Body() deletePageDto: DeletePageDto) {
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 getRecentWorkspacePages(@JwtUser() jwtUser) {
const workspaceId = (
await this.workspaceService.getUserCurrentWorkspace(jwtUser.id)
).id;
return this.pageService.getRecentWorkspacePages(workspaceId);
}
@HttpCode(HttpStatus.OK)
@Post()
async getWorkspacePages(@JwtUser() jwtUser) {
const workspaceId = (
await this.workspaceService.getUserCurrentWorkspace(jwtUser.id)
).id;
return this.pageService.getSidebarPagesByWorkspaceId(workspaceId);
}
@HttpCode(HttpStatus.OK)
@Post('ordering')
async getWorkspacePageOrder(@JwtUser() jwtUser) {
const workspaceId = (
await this.workspaceService.getUserCurrentWorkspace(jwtUser.id)
).id;
return this.pageOrderService.getWorkspacePageOrder(workspaceId);
}
@HttpCode(HttpStatus.OK)
@Post('tree')
async workspacePageTree(@JwtUser() jwtUser) {
const workspaceId = (
await this.workspaceService.getUserCurrentWorkspace(jwtUser.id)
).id;
return this.pageOrderService.convertToTree(workspaceId);
}
@HttpCode(HttpStatus.OK)
@Post('/history')
async getPageHistory(@Body() dto: PageHistoryDto) {
return this.pageHistoryService.findHistoryByPageId(dto.pageId);
}
@HttpCode(HttpStatus.OK)
@Post('/history/details')
async get(@Body() dto: HistoryDetailsDto) {
return this.pageHistoryService.findOne(dto.id);
}
}

View File

@ -0,0 +1,31 @@
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 { AuthModule } from '../auth/auth.module';
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]),
AuthModule,
WorkspaceModule,
],
controllers: [PageController],
providers: [
PageService,
PageOrderingService,
PageHistoryService,
PageRepository,
PageHistoryRepository,
],
exports: [PageService, PageOrderingService, PageHistoryService],
})
export class PageModule {}

View File

@ -0,0 +1,81 @@
import { MovePageDto } from './dto/move-page.dto';
import { EntityManager } from 'typeorm';
export enum OrderingEntity {
workspace = 'WORKSPACE',
page = 'PAGE',
}
export type TreeNode = {
id: string;
title: string;
icon?: string;
children?: TreeNode[];
};
export function orderPageList(arr: string[], payload: MovePageDto): void {
const { 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 save the entity
* @param entity - The entity instance (Page or Workspace)
* @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,
arrayField: string,
itemToRemove: any,
manager: EntityManager,
) {
const array = entity[arrayField];
const index = array.indexOf(itemToRemove);
if (index > -1) {
array.splice(index, 1);
await manager.save(entity);
}
}
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] = [];
} else {
processedRow[newKey] = row[key];
}
}
return processedRow;
});
}

View File

@ -0,0 +1,26 @@
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

@ -0,0 +1,56 @@
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.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

@ -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;
}
}

View 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[];
}
}

View 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();
});
});

View 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;
}
}

View File

@ -0,0 +1,2 @@
export const STORAGE_DRIVER_TOKEN = 'STORAGE_DRIVER_TOKEN';
export const STORAGE_CONFIG_TOKEN = 'STORAGE_CONFIG_TOKEN';

View File

@ -0,0 +1,2 @@
export { LocalDriver } from './local.driver';
export { S3Driver } from './s3.driver';

View File

@ -0,0 +1,71 @@
import {
StorageDriver,
LocalStorageConfig,
StorageOption,
} from '../interfaces';
import { join } from 'path';
import * as fs from 'fs-extra';
export class LocalDriver implements StorageDriver {
private readonly config: LocalStorageConfig;
constructor(config: LocalStorageConfig) {
this.config = config;
}
private _fullPath(filePath: string): string {
return join(this.config.storagePath, filePath);
}
async upload(filePath: string, file: Buffer): Promise<void> {
try {
await fs.outputFile(this._fullPath(filePath), file);
} catch (error) {
throw new Error(`Failed to upload file: ${error.message}`);
}
}
async read(filePath: string): Promise<Buffer> {
try {
return await fs.readFile(this._fullPath(filePath));
} catch (error) {
throw new Error(`Failed to read file: ${error.message}`);
}
}
async exists(filePath: string): Promise<boolean> {
try {
return await fs.pathExists(this._fullPath(filePath));
} catch (error) {
throw new Error(`Failed to check file existence: ${error.message}`);
}
}
async getSignedUrl(filePath: string, expireIn: number): Promise<string> {
throw new Error('Signed URLs are not supported for local storage.');
}
getUrl(filePath: string): string {
return this._fullPath(filePath);
}
async delete(filePath: string): Promise<void> {
try {
await fs.remove(this._fullPath(filePath));
} catch (error) {
throw new Error(`Failed to delete file: ${error.message}`);
}
}
getDriver(): typeof fs {
return fs;
}
getDriverName(): string {
return StorageOption.LOCAL;
}
getConfig(): Record<string, any> {
return this.config;
}
}

View File

@ -0,0 +1,115 @@
import { S3StorageConfig, StorageDriver, StorageOption } from '../interfaces';
import {
DeleteObjectCommand,
GetObjectCommand,
HeadObjectCommand,
NoSuchKey,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3';
import { streamToBuffer } from '../storage.utils';
import { Readable } from 'stream';
import * as mime from 'mime-types';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
export class S3Driver implements StorageDriver {
private readonly s3Client: S3Client;
private readonly config: S3StorageConfig;
constructor(config: S3StorageConfig) {
this.config = config;
this.s3Client = new S3Client(config as any);
}
async upload(filePath: string, file: Buffer): Promise<void> {
try {
const contentType =
mime.contentType(filePath) || 'application/octet-stream';
const command = new PutObjectCommand({
Bucket: this.config.bucket,
Key: filePath,
Body: file,
ContentType: contentType,
// ACL: "public-read",
});
await this.s3Client.send(command);
// we can get the path from location
console.log(`File uploaded successfully: ${filePath}`);
} catch (error) {
throw new Error(`Failed to upload file: ${error.message}`);
}
}
async read(filePath: string): Promise<Buffer> {
try {
const command = new GetObjectCommand({
Bucket: this.config.bucket,
Key: filePath,
});
const response = await this.s3Client.send(command);
return streamToBuffer(response.Body as Readable);
} catch (error) {
throw new Error(`Failed to read file from S3: ${error.message}`);
}
}
async exists(filePath: string): Promise<boolean> {
try {
const command = new HeadObjectCommand({
Bucket: this.config.bucket,
Key: filePath,
});
await this.s3Client.send(command);
return true;
} catch (err) {
if (err instanceof NoSuchKey) {
return false;
}
throw err;
}
}
getUrl(filePath: string): string {
return `${this.config.endpoint}/${this.config.bucket}/${filePath}`;
}
async getSignedUrl(filePath: string, expiresIn: number): Promise<string> {
const command = new GetObjectCommand({
Bucket: this.config.bucket,
Key: filePath,
});
return await getSignedUrl(this.s3Client, command, { expiresIn });
}
async delete(filePath: string): Promise<void> {
try {
const command = new DeleteObjectCommand({
Bucket: this.config.bucket,
Key: filePath,
});
await this.s3Client.send(command);
} catch (err) {
throw new Error(
`Error deleting file ${filePath} from S3. ${err.message}`,
);
}
}
getDriver(): S3Client {
return this.s3Client;
}
getDriverName(): string {
return StorageOption.S3;
}
getConfig(): Record<string, any> {
return this.config;
}
}

View File

@ -0,0 +1,2 @@
export * from './storage-driver.interface';
export * from './storage.interface';

View File

@ -0,0 +1,19 @@
export interface StorageDriver {
upload(filePath: string, file: Buffer): Promise<void>;
read(filePath: string): Promise<Buffer>;
exists(filePath: string): Promise<boolean>;
getUrl(filePath: string): string;
getSignedUrl(filePath: string, expireIn: number): Promise<string>;
delete(filePath: string): Promise<void>;
getDriver(): any;
getDriverName(): string;
getConfig(): Record<string, any>;
}

View File

@ -0,0 +1,33 @@
import { S3ClientConfig } from '@aws-sdk/client-s3';
export enum StorageOption {
LOCAL = 'local',
S3 = 's3',
}
export type StorageConfig =
| { driver: StorageOption.LOCAL; config: LocalStorageConfig }
| { driver: StorageOption.S3; config: S3StorageConfig };
export interface LocalStorageConfig {
storagePath: string;
}
export interface S3StorageConfig
extends Omit<S3ClientConfig, 'endpoint' | 'bucket'> {
endpoint: string; // Enforce endpoint
bucket: string; // Enforce bucket
baseUrl?: string; // Optional CDN URL for assets
}
export interface StorageOptions {
disk: StorageConfig;
}
export interface StorageOptionsFactory {
createStorageOptions(): Promise<StorageConfig> | StorageConfig;
}
export interface StorageModuleOptions {
imports?: any[];
}

View File

@ -0,0 +1,66 @@
import {
STORAGE_CONFIG_TOKEN,
STORAGE_DRIVER_TOKEN,
} from '../constants/storage.constants';
import { EnvironmentService } from '../../../environment/environment.service';
import {
LocalStorageConfig,
S3StorageConfig,
StorageConfig,
StorageDriver,
StorageOption,
} from '../interfaces';
import { LocalDriver, S3Driver } from '../drivers';
function createStorageDriver(disk: StorageConfig): StorageDriver {
switch (disk.driver) {
case StorageOption.LOCAL:
return new LocalDriver(disk.config as LocalStorageConfig);
case StorageOption.S3:
return new S3Driver(disk.config as S3StorageConfig);
default:
throw new Error(`Unknown storage driver`);
}
}
export const storageDriverConfigProvider = {
provide: STORAGE_CONFIG_TOKEN,
useFactory: async (environmentService: EnvironmentService) => {
const driver = environmentService.getStorageDriver();
if (driver === StorageOption.LOCAL) {
return {
driver,
config: {
storagePath:
process.cwd() + '/' + environmentService.getLocalStoragePath(),
},
};
}
if (driver === StorageOption.S3) {
return {
driver,
config: {
region: environmentService.getAwsS3Region(),
endpoint: environmentService.getAwsS3Endpoint(),
bucket: environmentService.getAwsS3Bucket(),
credentials: {
accessKeyId: environmentService.getAwsS3AccessKeyId(),
secretAccessKey: environmentService.getAwsS3SecretAccessKey(),
},
},
};
}
throw new Error(`Unknown storage driver: ${driver}`);
},
inject: [EnvironmentService],
};
export const storageDriverProvider = {
provide: STORAGE_DRIVER_TOKEN,
useFactory: (config) => createStorageDriver(config),
inject: [STORAGE_CONFIG_TOKEN],
};

View File

@ -0,0 +1,24 @@
import { DynamicModule, Global, Module } from '@nestjs/common';
import { StorageModuleOptions } from './interfaces';
import { StorageService } from './storage.service';
import {
storageDriverConfigProvider,
storageDriverProvider,
} from './providers/storage.provider';
@Global()
@Module({})
export class StorageModule {
static forRootAsync(options: StorageModuleOptions): DynamicModule {
return {
module: StorageModule,
imports: options.imports || [],
providers: [
storageDriverConfigProvider,
storageDriverProvider,
StorageService,
],
exports: [StorageService],
};
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { StorageService } from './storage.service';
describe('StorageService', () => {
let service: StorageService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [StorageService],
}).compile();
service = module.get<StorageService>(StorageService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,34 @@
import { Inject, Injectable } from '@nestjs/common';
import { STORAGE_DRIVER_TOKEN } from './constants/storage.constants';
import { StorageDriver } from './interfaces';
@Injectable()
export class StorageService {
constructor(
@Inject(STORAGE_DRIVER_TOKEN) private storageDriver: StorageDriver,
) {}
async upload(filePath: string, fileContent: Buffer | any) {
await this.storageDriver.upload(filePath, fileContent);
}
async read(filePath: string): Promise<Buffer> {
return this.storageDriver.read(filePath);
}
async exists(filePath: string): Promise<boolean> {
return this.storageDriver.exists(filePath);
}
async signedUrl(path: string, expireIn: number): Promise<string> {
return this.storageDriver.getSignedUrl(path, expireIn);
}
url(filePath: string): string {
return this.storageDriver.getUrl(filePath);
}
async delete(filePath: string): Promise<void> {
await this.storageDriver.delete(filePath);
}
}

View File

@ -0,0 +1,10 @@
import { Readable } from 'stream';
export function streamToBuffer(readableStream: Readable): Promise<Buffer> {
return new Promise((resolve, reject) => {
const chunks: Uint8Array[] = [];
readableStream.on('data', (chunk) => chunks.push(chunk));
readableStream.on('end', () => resolve(Buffer.concat(chunks)));
readableStream.on('error', reject);
});
}

View File

@ -0,0 +1,23 @@
import {
IsEmail,
IsNotEmpty,
IsOptional,
IsString,
MinLength,
} from 'class-validator';
export class CreateUserDto {
@IsOptional()
@MinLength(3)
@IsString()
name: string;
@IsNotEmpty()
@IsEmail()
email: string;
@IsNotEmpty()
@MinLength(8)
@IsString()
password: string;
}

View File

@ -0,0 +1,9 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateUserDto } from './create-user.dto';
import { IsOptional, IsString } from 'class-validator';
export class UpdateUserDto extends PartialType(CreateUserDto) {
@IsOptional()
@IsString()
avatarUrl: string;
}

View File

@ -0,0 +1,79 @@
import {
BeforeInsert,
Column,
CreateDateColumn,
Entity,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import * as bcrypt from 'bcrypt';
import { Workspace } from '../../workspace/entities/workspace.entity';
import { WorkspaceUser } from '../../workspace/entities/workspace-user.entity';
import { Page } from '../../page/entities/page.entity';
import { Comment } from '../../comment/entities/comment.entity';
@Entity('users')
export class User {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ length: 255, nullable: true })
name: string;
@Column({ length: 255, unique: true })
email: string;
@Column({ nullable: true })
emailVerifiedAt: Date;
@Column()
password: string;
@Column({ nullable: true })
avatarUrl: string;
@Column({ length: 100, nullable: true })
locale: string;
@Column({ length: 300, nullable: true })
timezone: string;
@Column({ type: 'jsonb', nullable: true })
settings: any;
@Column({ nullable: true })
lastLoginAt: Date;
@Column({ length: 100, nullable: true })
lastLoginIp: string;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@OneToMany(() => Workspace, (workspace) => workspace.creator)
workspaces: Workspace[];
@OneToMany(() => WorkspaceUser, (workspaceUser) => workspaceUser.user)
workspaceUsers: WorkspaceUser[];
@OneToMany(() => Page, (page) => page.creator)
createdPages: Page[];
@OneToMany(() => Comment, (comment) => comment.creator)
comments: Comment[];
toJSON() {
delete this.password;
return this;
}
@BeforeInsert()
async hashPassword() {
const saltRounds = 12;
this.password = await bcrypt.hash(this.password, saltRounds);
}
}

View File

@ -0,0 +1,17 @@
import { DataSource, Repository } from 'typeorm';
import { User } from '../entities/user.entity';
import { Injectable } from '@nestjs/common';
@Injectable()
export class UserRepository extends Repository<User> {
constructor(private dataSource: DataSource) {
super(User, dataSource.createEntityManager());
}
async findByEmail(email: string) {
return this.findOneBy({ email: email });
}
async findById(userId: string) {
return this.findOneBy({ id: userId });
}
}

View File

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UserController } from './user.controller';
import { UserService } from './user.service';
describe('UserController', () => {
let controller: UserController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UserController],
providers: [UserService],
}).compile();
controller = module.get<UserController>(UserController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,58 @@
import {
Controller,
Get,
UseGuards,
HttpCode,
HttpStatus,
Req,
UnauthorizedException,
Post,
Body,
} from '@nestjs/common';
import { UserService } from './user.service';
import { JwtGuard } from '../auth/guards/JwtGuard';
import { FastifyRequest } from 'fastify';
import { User } from './entities/user.entity';
import { Workspace } from '../workspace/entities/workspace.entity';
import { UpdateUserDto } from './dto/update-user.dto';
@UseGuards(JwtGuard)
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
@HttpCode(HttpStatus.OK)
@Get('me')
async getUser(@Req() req: FastifyRequest) {
const jwtPayload = req['user'];
const user: User = await this.userService.findById(jwtPayload.sub);
if (!user) {
throw new UnauthorizedException('Invalid user');
}
return { user };
}
@HttpCode(HttpStatus.OK)
@Get('info')
async getUserInfo(@Req() req: FastifyRequest) {
const jwtPayload = req['user'];
const data: { workspace: Workspace; user: User } =
await this.userService.getUserInstance(jwtPayload.sub);
return data;
}
@HttpCode(HttpStatus.OK)
@Post('update')
async updateUser(
@Req() req: FastifyRequest,
@Body() updateUserDto: UpdateUserDto,
) {
const jwtPayload = req['user'];
return this.userService.update(jwtPayload.sub, updateUserDto);
}
}

View File

@ -0,0 +1,20 @@
import { forwardRef, Module } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { UserRepository } from './repositories/user.repository';
import { AuthModule } from '../auth/auth.module';
import { WorkspaceModule } from '../workspace/workspace.module';
@Module({
imports: [
TypeOrmModule.forFeature([User]),
forwardRef(() => AuthModule),
WorkspaceModule,
],
controllers: [UserController],
providers: [UserService, UserRepository],
exports: [UserService, UserRepository],
})
export class UserModule {}

View File

@ -0,0 +1,77 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './user.service';
import { UserRepository } from './repositories/user.repository';
import { User } from './entities/user.entity';
import { BadRequestException } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
describe('UserService', () => {
let userService: UserService;
let userRepository: any;
const mockUserRepository = () => ({
findByEmail: jest.fn(),
save: jest.fn(),
});
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UserService,
{
provide: UserRepository,
useFactory: mockUserRepository,
},
],
}).compile();
userService = module.get<UserService>(UserService);
userRepository = module.get<UserRepository>(UserRepository);
});
it('should be defined', () => {
expect(userService).toBeDefined();
expect(userRepository).toBeDefined();
});
describe('create', () => {
const createUserDto: CreateUserDto = {
name: 'John Doe',
email: 'test@test.com',
password: 'password',
};
it('should throw an error if a user with this email already exists', async () => {
userRepository.findByEmail.mockResolvedValue(new User());
await expect(userService.create(createUserDto)).rejects.toThrow(
BadRequestException,
);
});
it('should create the user if it does not already exist', async () => {
const savedUser = {
...createUserDto,
id: expect.any(String),
createdAt: expect.any(Date),
updatedAt: expect.any(Date),
lastLoginAt: expect.any(Date),
locale: 'en',
emailVerifiedAt: null,
avatar_url: null,
timezone: null,
settings: null,
lastLoginIp: null,
};
userRepository.findByEmail.mockResolvedValue(undefined);
userRepository.save.mockResolvedValue(savedUser);
const result = await userService.create(createUserDto);
expect(result).toMatchObject(savedUser);
expect(userRepository.save).toHaveBeenCalledWith(
expect.objectContaining(createUserDto),
);
});
});
});

View File

@ -0,0 +1,85 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';
import { UserRepository } from './repositories/user.repository';
import { plainToInstance } from 'class-transformer';
import * as bcrypt from 'bcrypt';
import { WorkspaceService } from '../workspace/services/workspace.service';
import { Workspace } from '../workspace/entities/workspace.entity';
@Injectable()
export class UserService {
constructor(
private userRepository: UserRepository,
private workspaceService: WorkspaceService,
) {}
async create(createUserDto: CreateUserDto): Promise<User> {
const existingUser: User = await this.findByEmail(createUserDto.email);
if (existingUser) {
throw new BadRequestException('A user with this email already exists');
}
let user: User = plainToInstance(User, createUserDto);
user.locale = 'en';
user.lastLoginAt = new Date();
user = await this.userRepository.save(user);
//TODO: only create workspace if it is not a signup to an existing workspace
await this.workspaceService.create(user.id);
return user;
}
async getUserInstance(userId: string) {
const user: User = await this.findById(userId);
const workspace: Workspace =
await this.workspaceService.getUserCurrentWorkspace(userId);
return { user, workspace };
}
async findById(userId: string) {
return this.userRepository.findById(userId);
}
async findByEmail(email: string) {
return this.userRepository.findByEmail(email);
}
async update(userId: string, updateUserDto: UpdateUserDto) {
const user = await this.userRepository.findById(userId);
if (!user) {
throw new NotFoundException('User not found');
}
if (updateUserDto.name) {
user.name = updateUserDto.name;
}
if (updateUserDto.email && user.email != updateUserDto.email) {
if (await this.userRepository.findByEmail(updateUserDto.email)) {
throw new BadRequestException('A user with this email already exists');
}
user.email = updateUserDto.email;
}
if (updateUserDto.avatarUrl) {
user.avatarUrl = updateUserDto.avatarUrl;
}
return this.userRepository.save(user);
}
async compareHash(
plainPassword: string,
passwordHash: string,
): Promise<boolean> {
return await bcrypt.compare(plainPassword, passwordHash);
}
}

View File

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { WorkspaceController } from './workspace.controller';
import { WorkspaceService } from '../services/workspace.service';
describe('WorkspaceController', () => {
let controller: WorkspaceController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [WorkspaceController],
providers: [WorkspaceService],
}).compile();
controller = module.get<WorkspaceController>(WorkspaceController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,120 @@
import {
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import { WorkspaceService } from '../services/workspace.service';
import { FastifyRequest } from 'fastify';
import { JwtGuard } from '../../auth/guards/JwtGuard';
import { UpdateWorkspaceDto } from '../dto/update-workspace.dto';
import { CreateWorkspaceDto } from '../dto/create-workspace.dto';
import { DeleteWorkspaceDto } from '../dto/delete-workspace.dto';
import { UpdateWorkspaceUserRoleDto } from '../dto/update-workspace-user-role.dto';
import { RemoveWorkspaceUserDto } from '../dto/remove-workspace-user.dto';
import { AddWorkspaceUserDto } from '../dto/add-workspace-user.dto';
@UseGuards(JwtGuard)
@Controller('workspace')
export class WorkspaceController {
constructor(private readonly workspaceService: WorkspaceService) {}
@HttpCode(HttpStatus.OK)
@Post('create')
async createWorkspace(
@Req() req: FastifyRequest,
@Body() createWorkspaceDto: CreateWorkspaceDto,
) {
const jwtPayload = req['user'];
const userId = jwtPayload.sub;
return this.workspaceService.create(userId, createWorkspaceDto);
}
@HttpCode(HttpStatus.OK)
@Post('update')
async updateWorkspace(
@Req() req: FastifyRequest,
@Body() updateWorkspaceDto: UpdateWorkspaceDto,
) {
const jwtPayload = req['user'];
const workspaceId = (
await this.workspaceService.getUserCurrentWorkspace(jwtPayload.sub)
).id;
return this.workspaceService.update(workspaceId, updateWorkspaceDto);
}
@HttpCode(HttpStatus.OK)
@Post('delete')
async deleteWorkspace(@Body() deleteWorkspaceDto: DeleteWorkspaceDto) {
return this.workspaceService.delete(deleteWorkspaceDto);
}
@HttpCode(HttpStatus.OK)
@Get('members')
async getWorkspaceMembers(@Req() req: FastifyRequest) {
const jwtPayload = req['user'];
const workspaceId = (
await this.workspaceService.getUserCurrentWorkspace(jwtPayload.sub)
).id;
return this.workspaceService.getWorkspaceUsers(workspaceId);
}
@HttpCode(HttpStatus.OK)
@Post('members/add')
async addWorkspaceMember(
@Req() req: FastifyRequest,
@Body() addWorkspaceUserDto: AddWorkspaceUserDto,
) {
const jwtPayload = req['user'];
const workspaceId = (
await this.workspaceService.getUserCurrentWorkspace(jwtPayload.sub)
).id;
return this.workspaceService.addUserToWorkspace(
addWorkspaceUserDto.userId,
workspaceId,
addWorkspaceUserDto.role,
);
}
@HttpCode(HttpStatus.OK)
@Delete('members/delete')
async removeWorkspaceMember(
@Req() req: FastifyRequest,
@Body() removeWorkspaceUserDto: RemoveWorkspaceUserDto,
) {
const jwtPayload = req['user'];
const workspaceId = (
await this.workspaceService.getUserCurrentWorkspace(jwtPayload.sub)
).id;
return this.workspaceService.removeUserFromWorkspace(
removeWorkspaceUserDto.userId,
workspaceId,
);
}
@HttpCode(HttpStatus.OK)
@Post('members/role')
async updateWorkspaceMemberRole(
@Req() req: FastifyRequest,
@Body() workspaceUserRoleDto: UpdateWorkspaceUserRoleDto,
) {
const jwtPayload = req['user'];
const workspaceId = (
await this.workspaceService.getUserCurrentWorkspace(jwtPayload.sub)
).id;
return this.workspaceService.updateWorkspaceUserRole(
workspaceUserRoleDto,
workspaceId,
);
}
}

View File

@ -0,0 +1,11 @@
import { IsNotEmpty, IsString, IsUUID } from 'class-validator';
export class AddWorkspaceUserDto {
@IsNotEmpty()
@IsUUID()
userId: string;
@IsNotEmpty()
@IsString()
role: string;
}

View File

@ -0,0 +1,18 @@
import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
export class CreateWorkspaceDto {
@MinLength(4)
@MaxLength(64)
@IsString()
name: string;
@IsOptional()
@MinLength(4)
@MaxLength(30)
@IsString()
hostname?: string;
@IsOptional()
@IsString()
description?: string;
}

View File

@ -0,0 +1,6 @@
import { IsString } from 'class-validator';
export class DeleteWorkspaceDto {
@IsString()
workspaceId: string;
}

View File

@ -0,0 +1,7 @@
import { IsNotEmpty, IsUUID } from 'class-validator';
export class RemoveWorkspaceUserDto {
@IsNotEmpty()
@IsUUID()
userId: string;
}

View File

@ -0,0 +1,11 @@
import { IsNotEmpty, IsString, IsUUID } from 'class-validator';
export class UpdateWorkspaceUserRoleDto {
@IsNotEmpty()
@IsUUID()
userId: string;
@IsNotEmpty()
@IsString()
role: string;
}

View File

@ -0,0 +1,9 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateWorkspaceDto } from './create-workspace.dto';
import { IsOptional, IsString } from 'class-validator';
export class UpdateWorkspaceDto extends PartialType(CreateWorkspaceDto) {
@IsOptional()
@IsString()
logo: string;
}

View File

@ -0,0 +1,48 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';
import { Workspace } from './workspace.entity';
import { User } from '../../user/entities/user.entity';
@Entity('workspace_invitations')
export class WorkspaceInvitation {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
workspaceId: string;
@ManyToOne(() => Workspace, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'workspaceId' })
workspace: Workspace;
@Column()
invitedById: string;
@ManyToOne(() => User)
@JoinColumn({ name: 'invitedById' })
invitedBy: User;
@Column({ length: 255 })
email: string;
@Column({ length: 100, nullable: true })
role: string;
@Column({ length: 100, nullable: true })
status: string;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}

View File

@ -0,0 +1,46 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
Unique,
} from 'typeorm';
import { Workspace } from './workspace.entity';
import { User } from '../../user/entities/user.entity';
@Entity('workspace_users')
@Unique(['workspaceId', 'userId'])
export class WorkspaceUser {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
userId: string;
@ManyToOne(() => User, (user) => user.workspaceUsers, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'userId' })
user: User;
@Column()
workspaceId: string;
@ManyToOne(() => Workspace, (workspace) => workspace.workspaceUsers, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'workspaceId' })
workspace: Workspace;
@Column({ length: 100, nullable: true })
role: string;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}

View File

@ -0,0 +1,73 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
OneToMany,
JoinColumn,
} from 'typeorm';
import { User } from '../../user/entities/user.entity';
import { WorkspaceUser } from './workspace-user.entity';
import { Page } from '../../page/entities/page.entity';
import { WorkspaceInvitation } from './workspace-invitation.entity';
import { Comment } from '../../comment/entities/comment.entity';
@Entity('workspaces')
export class Workspace {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ length: 255, nullable: true })
name: string;
@Column({ type: 'text', nullable: true })
description: string;
@Column({ length: 255, nullable: true })
logo: string;
@Column({ length: 255, nullable: true, unique: true })
hostname: string;
@Column({ length: 255, nullable: true })
customDomain: string;
@Column({ type: 'boolean', default: true })
enableInvite: boolean;
@Column({ length: 255, unique: true, nullable: true })
inviteCode: string;
@Column({ type: 'jsonb', nullable: true })
settings: any;
@Column()
creatorId: string;
@ManyToOne(() => User, (user) => user.workspaces)
@JoinColumn({ name: 'creatorId' })
creator: User;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@OneToMany(() => WorkspaceUser, (workspaceUser) => workspaceUser.workspace)
workspaceUsers: WorkspaceUser[];
@OneToMany(
() => WorkspaceInvitation,
(workspaceInvitation) => workspaceInvitation.workspace,
)
workspaceInvitations: WorkspaceInvitation[];
@OneToMany(() => Page, (page) => page.workspace)
pages: Page[];
@OneToMany(() => Comment, (comment) => comment.workspace)
comments: Comment[];
}

View File

@ -0,0 +1,10 @@
import { Injectable } from '@nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { WorkspaceUser } from '../entities/workspace-user.entity';
@Injectable()
export class WorkspaceUserRepository extends Repository<WorkspaceUser> {
constructor(private dataSource: DataSource) {
super(WorkspaceUser, dataSource.createEntityManager());
}
}

View File

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

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { WorkspaceService } from './workspace.service';
describe('WorkspaceService', () => {
let service: WorkspaceService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [WorkspaceService],
}).compile();
service = module.get<WorkspaceService>(WorkspaceService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,201 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { CreateWorkspaceDto } from '../dto/create-workspace.dto';
import { WorkspaceRepository } from '../repositories/workspace.repository';
import { WorkspaceUserRepository } from '../repositories/workspace-user.repository';
import { WorkspaceUser } from '../entities/workspace-user.entity';
import { Workspace } from '../entities/workspace.entity';
import { plainToInstance } from 'class-transformer';
import { v4 as uuid } from 'uuid';
import { generateHostname } from '../workspace.util';
import { UpdateWorkspaceDto } from '../dto/update-workspace.dto';
import { DeleteWorkspaceDto } from '../dto/delete-workspace.dto';
import { UpdateWorkspaceUserRoleDto } from '../dto/update-workspace-user-role.dto';
@Injectable()
export class WorkspaceService {
constructor(
private workspaceRepository: WorkspaceRepository,
private workspaceUserRepository: WorkspaceUserRepository,
) {}
async findById(workspaceId: string): Promise<Workspace> {
return this.workspaceRepository.findById(workspaceId);
}
async save(workspace: Workspace) {
return this.workspaceRepository.save(workspace);
}
async create(
userId: string,
createWorkspaceDto?: CreateWorkspaceDto,
): Promise<Workspace> {
let workspace: Workspace;
if (createWorkspaceDto) {
workspace = plainToInstance(Workspace, createWorkspaceDto);
} else {
workspace = new Workspace();
}
workspace.inviteCode = uuid();
workspace.creatorId = userId;
if (workspace.name && !workspace.hostname?.trim()) {
workspace.hostname = generateHostname(createWorkspaceDto.name);
}
workspace = await this.workspaceRepository.save(workspace);
await this.addUserToWorkspace(userId, workspace.id, 'owner');
return workspace;
}
async update(
workspaceId: string,
updateWorkspaceDto: UpdateWorkspaceDto,
): Promise<Workspace> {
const workspace = await this.workspaceRepository.findById(workspaceId);
if (!workspace) {
throw new NotFoundException('Workspace not found');
}
if (updateWorkspaceDto.name) {
workspace.name = updateWorkspaceDto.name;
}
if (updateWorkspaceDto.logo) {
workspace.logo = updateWorkspaceDto.logo;
}
return this.workspaceRepository.save(workspace);
}
async delete(deleteWorkspaceDto: DeleteWorkspaceDto): Promise<void> {
const workspace = await this.workspaceRepository.findById(
deleteWorkspaceDto.workspaceId,
);
if (!workspace) {
throw new NotFoundException('Workspace not found');
}
//TODO
// remove all existing users from workspace
// delete workspace
}
async addUserToWorkspace(
userId: string,
workspaceId: string,
role: string,
): Promise<WorkspaceUser> {
const existingWorkspaceUser = await this.workspaceUserRepository.findOne({
where: { userId: userId, workspaceId: workspaceId },
});
if (existingWorkspaceUser) {
throw new BadRequestException('User already added to this workspace');
}
const workspaceUser = new WorkspaceUser();
workspaceUser.userId = userId;
workspaceUser.workspaceId = workspaceId;
workspaceUser.role = role;
return this.workspaceUserRepository.save(workspaceUser);
}
async updateWorkspaceUserRole(
workspaceUserRoleDto: UpdateWorkspaceUserRoleDto,
workspaceId: string,
) {
const workspaceUser = await this.workspaceUserRepository.findOne({
where: { userId: workspaceUserRoleDto.userId, workspaceId: workspaceId },
});
if (!workspaceUser) {
throw new BadRequestException('user is not a member of this workspace');
}
if (workspaceUser.role === workspaceUserRoleDto.role) {
return workspaceUser;
}
workspaceUser.role = workspaceUserRoleDto.role;
// TODO: if there is only one workspace owner, prevent the role change
return this.workspaceUserRepository.save(workspaceUser);
}
async removeUserFromWorkspace(
userId: string,
workspaceId: string,
): Promise<void> {
await this.validateWorkspaceMember(userId, workspaceId);
await this.workspaceUserRepository.delete({
userId,
workspaceId,
});
}
async getUserCurrentWorkspace(userId: string): Promise<Workspace> {
// TODO: use workspaceId and fetch workspace based on the id
// we currently assume the user belongs to one workspace
const userWorkspace = await this.workspaceUserRepository.findOne({
where: { userId: userId },
relations: ['workspace'],
});
return userWorkspace.workspace;
}
async getUserWorkspaces(userId: string): Promise<Workspace[]> {
const workspaces = await this.workspaceUserRepository.find({
where: { userId: userId },
relations: ['workspace'],
});
return workspaces.map(
(userWorkspace: WorkspaceUser) => userWorkspace.workspace,
);
}
async getWorkspaceUsers(workspaceId: string) {
const workspace = await this.workspaceRepository.findOne({
where: { id: workspaceId },
relations: ['workspaceUsers', 'workspaceUsers.user'],
});
if (!workspace) {
throw new BadRequestException('Invalid workspace');
}
const users = workspace.workspaceUsers.map((workspaceUser) => {
workspaceUser.user.password = '';
return {
...workspaceUser.user,
workspaceRole: workspaceUser.role,
};
});
return { users };
}
async validateWorkspaceMember(
userId: string,
workspaceId: string,
): Promise<void> {
const workspaceUser = await this.workspaceUserRepository.findOne({
where: { userId, workspaceId },
});
if (!workspaceUser) {
throw new BadRequestException('User is not a member of this workspace');
}
}
}

View File

@ -0,0 +1,21 @@
import { Module } from '@nestjs/common';
import { WorkspaceService } from './services/workspace.service';
import { WorkspaceController } from './controllers/workspace.controller';
import { WorkspaceRepository } from './repositories/workspace.repository';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Workspace } from './entities/workspace.entity';
import { WorkspaceUser } from './entities/workspace-user.entity';
import { WorkspaceInvitation } from './entities/workspace-invitation.entity';
import { WorkspaceUserRepository } from './repositories/workspace-user.repository';
import { AuthModule } from '../auth/auth.module';
@Module({
imports: [
TypeOrmModule.forFeature([Workspace, WorkspaceUser, WorkspaceInvitation]),
AuthModule,
],
controllers: [WorkspaceController],
providers: [WorkspaceService, WorkspaceRepository, WorkspaceUserRepository],
exports: [WorkspaceService, WorkspaceRepository, WorkspaceUserRepository],
})
export class WorkspaceModule {}

View File

@ -0,0 +1,5 @@
export function generateHostname(name: string): string {
let hostname = name.replace(/[^a-z0-9]/gi, '').toLowerCase();
hostname = hostname.substring(0, 30);
return hostname;
}

View File

@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppDataSource } from './typeorm.config';
@Module({
imports: [
TypeOrmModule.forRoot({
...AppDataSource.options,
entities: ['dist/src/**/*.entity.{ts,js}'],
migrations: ['dist/src/**/migrations/*.{ts,js}'],
autoLoadEntities: true,
}),
],
})
export class DatabaseModule {}

Some files were not shown because too many files have changed in this diff Show More