웹소켓이나 server-sent event 같은 특정한 프로토콜을 사용하지 않아도 아주 간단한 서버오 지속적인 커넥션을 유지할 수 있음
구현이 매우 쉽고 다양한 경우 사용 가능
지연없이 메시지를 전달한다
client → request 보냄
server → response 올때까지 기다림
response 받으면 바로 request 보냄
기존의 polling방식보다는 서버의 부담 ⬇️
reqest의 시간간격이 좁다면 polling과 별 차이 없어 클라이언트 많아지면 서버 부담⬆️ Traffic 발생
클라이언트에서 Long Polling 요청 초기화
서버에서 요청 처리
클라이언트에서 응답 처리
⇒ 사용자에게 실시간으로 댓글 알림을 제공
notification 디렉토리 생성
notification에 dto, contorller, service 생성
notification.dto 생성
조건
//notification.dto.ts
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
} from 'typeorm';
import { Board } from '../../board/entities/board.entity';
@Entity('notification')
export class Notification {
@PrimaryGeneratedColumn('increment', { name: 'notification_id' })
id: number;
@Column()
message: string;
@Column({ type: 'int', nullable: true })
nodeId: number;
@Column({ type: 'int', nullable: true })
user_id: number;
@ManyToOne(() => Board, { eager: true }) // eager를 true로 설정하여 자동으로 관련된 Board 정보를 가져올 수 있게 합니다.
@JoinColumn({ name: 'board_id' })
board: Board;
get userNickname(): string {
return this.board.user.nickname; // board 객체를 통해 user의 nickname을 가져옵니다. 이때 board의 user 객체는 eager 로딩되어 있어야 합니다.
}
}
user_id 와 noed_id는 board에서 가지고 오는 걸 dto에서 바로 쓰고 싶었지만 바로 쓰면 colum를 하지 못해 service에 board에서 데이터를 가지고 온다고 작성해줌. user_nickname은 dto에 정의해줌
comment 설정
조건
댓글을 달면 notification으로 연동이 되야 함
//comment.service.ts
/** 댓글 생성 */
async createComment(
boardId: number,
userId: string,
createCommentDto: CreateCommentDto,
): Promise<Comment> {
const convertedUserId = Number(userId);
const user = await this.userService.findUserById(convertedUserId);
if (!user) {
throw new UserNotFoundException();
}
const board = await this.boardService.findBoardById(boardId);
if (!board) {
throw new BoardNotFoundException();
}
const comment = this.commentMapper.DtoToEntity(
createCommentDto,
user,
board,
user.nickname,
);
const savedComment = await this.commentRepository.save(comment);
// 댓글이 성공적으로 생성된 후 알림 생성
const notificationData = {
board: board,
message: `${user.nickname}님이 ${board.title}에 댓글을 작성했습니다.`,
commentId: savedComment.id,
nodeId: board.nodeId,
userId: board.userId,
};
await this.notificationService.createNotificationForBoardOwner(
notificationData,
);
return savedComment;
}
댓글 생성 후 해당 댓글 정보와 게시판 소유자에게 알림을 보내는 기능을 구현한 것
this.notificationService.createNotificationForBoardOwner
함수의 구현 내용에 따라 알림이 어떻게 전송되고 처리되는지 정확히 알 수 있을 것