Skip to content

Socket.io 마인드맵 작업 동작 #377

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 32 commits into from
Feb 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
9302060
feat: 마인드맵 작업 로그 스키마
Conut-1 Feb 1, 2025
0c5f0b5
feat: 모듈에 BoardOperation 스키마 추가
Conut-1 Feb 1, 2025
68522c4
feat: 보드 작업 생성 요청
Conut-1 Feb 1, 2025
929927f
fix: 작업 DB에 저장
Conut-1 Feb 3, 2025
7620434
feat; 작업 로그 가져오기기
Conut-1 Feb 3, 2025
2244e2e
fix: gateway에서 트리 조작 제거
Conut-1 Feb 3, 2025
c45c5fc
test: board trees 테스트 모듈
Conut-1 Feb 4, 2025
1e041be
chore: socket.io-client 패키지 설치
Conut-1 Feb 4, 2025
d143d98
test: socket.io-client 동작 확인
Conut-1 Feb 4, 2025
531db28
test: 네임스페이스로 연결하도록 테스트 코드 변경경
Conut-1 Feb 5, 2025
a2a65d1
fix: 에러 throw 제거
Conut-1 Feb 5, 2025
588a59f
test: 연결 실패 시 connect_error 이벤트로 테스트 변경
Conut-1 Feb 6, 2025
89c5ab0
refactor: import 순서 변경
Conut-1 Feb 6, 2025
229977a
refactor: 서버 url 변수로 변경
Conut-1 Feb 6, 2025
33d9eba
test: 유효하지 않은 토큰 연결 테스트
Conut-1 Feb 6, 2025
96df965
fix: 사용자 인증을 afterInit에서 처리하도록 수정
Conut-1 Feb 6, 2025
7068559
test: 연결 성공 테스트트
Conut-1 Feb 6, 2025
b9a55c7
fix: secret 옵션 추가
Conut-1 Feb 6, 2025
1f670f5
test: 테스트 이름 변경
Conut-1 Feb 7, 2025
a4b4d29
test: 연결 시 boardId 확인
Conut-1 Feb 7, 2025
f62c9c7
feat: socket.io 연결 시에 보드 room에 join
Conut-1 Feb 7, 2025
d2c116e
fix: Error를 resolve대신 reject로 받기기
Conut-1 Feb 7, 2025
effa9dd
test: 보드 입장 테스트
Conut-1 Feb 7, 2025
fb6568c
refactor: serverUrl 상위 스코프로 이동
Conut-1 Feb 8, 2025
e4ee3f3
test: 작업 생성 테스트트
Conut-1 Feb 8, 2025
edf825e
fix: 작업 생성 인자 수정
Conut-1 Feb 8, 2025
5fde4ef
fix: select, lean 추가
Conut-1 Feb 8, 2025
d1f59c1
feat: 작업 생성에 대한 응답
Conut-1 Feb 8, 2025
9d396c5
test: 다른 유저에 작업 보내기 테스트
Conut-1 Feb 8, 2025
e5bfdc4
test: 작업 로그 가져오기 테스트
Conut-1 Feb 9, 2025
9f16602
refactor: 클라이언트 생성 함수
Conut-1 Feb 9, 2025
e32b012
refactor: 토큰 생성 함수
Conut-1 Feb 9, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions nestjs-BE/server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions nestjs-BE/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
"jest": "^29.5.0",
"prettier": "^3.0.0",
"prisma": "^5.6.0",
"socket.io-client": "^4.8.1",
"source-map-support": "^0.5.21",
"supertest": "^6.3.3",
"ts-jest": "^29.1.0",
Expand Down
91 changes: 40 additions & 51 deletions nestjs-BE/server/src/board-trees/board-trees.gateway.ts
Original file line number Diff line number Diff line change
@@ -1,78 +1,67 @@
import { UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import {
OnGatewayConnection,
OnGatewayInit,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
WsException,
} from '@nestjs/websockets';
import { ConfigService } from '@nestjs/config';
import { Server, Socket } from 'socket.io';
import { BoardTreesService } from './board-trees.service';
import {
OperationAdd,
OperationDelete,
OperationMove,
OperationUpdate,
} from '../crdt/operation';
import type { BoardOperation } from './schemas/board-operation.schema';

@WebSocketGateway({ namespace: 'board' })
export class BoardTreesGateway implements OnGatewayConnection {
export class BoardTreesGateway implements OnGatewayInit, OnGatewayConnection {
constructor(
private boardTreesService: BoardTreesService,
private jwtService: JwtService,
private configService: ConfigService,
) {}

@WebSocketServer()
server: Server;

handleConnection(client: Socket, token: string) {
if (!token) {
client.disconnect();
throw new UnauthorizedException();
}
try {
this.jwtService.verify(token);
} catch (error) {
client.disconnect();
throw new UnauthorizedException();
}
afterInit(server: Server) {
server.use((socket, next) => {
const token = socket.handshake.auth.token;
if (!token) {
next(new WsException('access token required'));
}
try {
this.jwtService.verify(token, {
secret: this.configService.get<string>('JWT_ACCESS_SECRET'),
});
next();
} catch (error) {
next(new WsException('token is invalid'));
}
});
}

@SubscribeMessage('joinBoard')
async handleJoinBoard(client: Socket, payload: string) {
const payloadObject = JSON.parse(payload);
if (!this.boardTreesService.hasTree(payloadObject.boardId)) {
await this.boardTreesService.initBoardTree(
payloadObject.boardId,
payloadObject.boardName,
);
handleConnection(client: Socket) {
const query = client.handshake.query;
const boardId = query.boardId;

if (!boardId) {
client.emit('board_id_required', new WsException('board id required'));
client.disconnect();
}
client.join(payloadObject.boardId);
client.emit(
'initTree',
this.boardTreesService.getTreeData(payloadObject.boardId),
);
client.join(boardId);
client.emit('board_joined', boardId);
}

@SubscribeMessage('updateMindmap')
handleUpdateMindmap(client: Socket, payload: string) {
const payloadObject = JSON.parse(payload);
const { boardId, operation: serializedOperation } = payloadObject;

const operationTypeMap = {
add: OperationAdd.parse,
delete: OperationDelete.parse,
move: OperationMove.parse,
update: OperationUpdate.parse,
};

const operation =
operationTypeMap[serializedOperation.operationType](serializedOperation);
this.boardTreesService.applyOperation(boardId, operation);
this.boardTreesService.updateTreeData(boardId);
@SubscribeMessage('createOperation')
async handleCreateOperation(client: Socket, operation: BoardOperation) {
await this.boardTreesService.createOperationLog(operation);
client.broadcast.to(operation.boardId).emit('operation', operation);
client.emit('operationCreated');
}

client.broadcast
.to(boardId)
.emit('operationFromServer', serializedOperation);
@SubscribeMessage('getOperations')
async handleGetOperations(client: Socket, boardId: string) {
const operations = await this.boardTreesService.getOperationLogs(boardId);
client.emit('getOperations', operations);
}
}
5 changes: 5 additions & 0 deletions nestjs-BE/server/src/board-trees/board-trees.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@ import { MongooseModule } from '@nestjs/mongoose';
import { BoardTreesService } from './board-trees.service';
import { BoardTreesGateway } from './board-trees.gateway';
import { BoardTree, BoardTreeSchema } from './schemas/board-tree.schema';
import {
BoardOperation,
BoardOperationSchema,
} from './schemas/board-operation.schema';

@Module({
imports: [
MongooseModule.forFeature([
{ name: BoardTree.name, schema: BoardTreeSchema },
{ name: BoardOperation.name, schema: BoardOperationSchema },
]),
JwtModule,
],
Expand Down
14 changes: 14 additions & 0 deletions nestjs-BE/server/src/board-trees/board-trees.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { BoardTree } from './schemas/board-tree.schema';
import { BoardOperation } from './schemas/board-operation.schema';
import { CrdtTree } from '../crdt/crdt-tree';
import { Operation } from '../crdt/operation';

@Injectable()
export class BoardTreesService {
constructor(
@InjectModel(BoardTree.name) private boardTreeModel: Model<BoardTree>,
@InjectModel(BoardOperation.name)
private boardOperationModel: Model<BoardOperation>,
) {}

private boardTrees = new Map<string, CrdtTree>();
Expand Down Expand Up @@ -57,4 +60,15 @@ export class BoardTreesService {
.updateOne({ boardId }, { tree: JSON.stringify(tree) })
.exec();
}

async createOperationLog(operation: BoardOperation) {
return this.boardOperationModel.create(operation);
}

async getOperationLogs(boardId: string) {
return this.boardOperationModel
.find({ boardId })
.select('-_id -__v')
.lean();
}
}
28 changes: 28 additions & 0 deletions nestjs-BE/server/src/board-trees/schemas/board-operation.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';

export type BoardOperationDocument = HydratedDocument<BoardOperation>;

@Schema()
export class BoardOperation {
@Prop({ required: true })
boardId: string;

@Prop({ required: true })
type: string;

@Prop()
parentId: string;

@Prop()
oldParentId: string;

@Prop()
content: string;

@Prop()
oldContent: string;
}

export const BoardOperationSchema =
SchemaFactory.createForClass(BoardOperation);
Loading