Long polling

웹소켓이나 server-sent event 같은 특정한 프로토콜을 사용하지 않아도 아주 간단한 서버오 지속적인 커넥션을 유지할 수 있음

구현이 매우 쉽고 다양한 경우 사용 가능

지연없이 메시지를 전달한다

기능

client → request 보냄

server → response 올때까지 기다림

response 받으면 바로 request 보냄

Untitled

기존의 polling방식보다는 서버의 부담 ⬇️

reqest의 시간간격이 좁다면 polling과 별 차이 없어 클라이언트 많아지면 서버 부담⬆️ Traffic 발생

Nestjs ↔ Long Polling

  1. 클라이언트에서 Long Polling 요청 초기화

  2. 서버에서 요청 처리

  3. 클라이언트에서 응답 처리

    ⇒ 사용자에게 실시간으로 댓글 알림을 제공

프로젝트 적용

  1. notification 디렉토리 생성

  2. notification에 dto, contorller, service 생성

  3. 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에 정의해줌

  4. comment 설정

    조건