<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by 완두콩 on Medium]]></title>
        <description><![CDATA[Stories by 완두콩 on Medium]]></description>
        <link>https://medium.com/@kawy.sojung?source=rss-48475f033e55------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VVwk1KAbtAeNL8ckPVGYNw.png</url>
            <title>Stories by 완두콩 on Medium</title>
            <link>https://medium.com/@kawy.sojung?source=rss-48475f033e55------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:18:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kawy.sojung/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Websocket 사용해보자!]]></title>
            <link>https://medium.com/@kawy.sojung/socket-io-%EC%82%AC%EC%9A%A9%ED%95%B4%EB%B3%B4%EC%9E%90-a67e3f894e76?source=rss-48475f033e55------2</link>
            <guid isPermaLink="false">https://medium.com/p/a67e3f894e76</guid>
            <dc:creator><![CDATA[완두콩]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 07:58:55 GMT</pubDate>
            <atom:updated>2024-11-06T16:21:36.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*BUnMPDDztGopSbpeNl2bvQ.jpeg" /></figure><blockquote><strong>Socket.io를 쓰는 이유는?</strong></blockquote><ul><li>“Socket.io 말고 Websocket도 있는데 굳이..?🤫”</li><li>“Polling 기능도 있는데 굳이..?🧐”</li><li>“Socket.io 장점이 몬데…Websocket이랑 뭐가 달라?😳”</li></ul><p>라는 궁금증이 생길 수 있다.</p><blockquote><strong>Websocket</strong></blockquote><ul><li>브로드캐스팅 ❌ (연결된 모든 사용자에게 메세지를 보내는 것)</li><li>fallback ❌ (자동 복구를 시도하지 않음)</li></ul><p>➡️ <strong>가상화폐 거래소 </strong>같이 데이터 전송이 많은 경우에는 빠르고 비용이 적은 표준 Websocket 이용이 바람직하다.</p><blockquote><strong>Socket.io</strong></blockquote><ul><li>브로드 캐스팅 ⭕️ (동시 메세지 보내서 서버 부하 단점이 있음)</li><li>fallback ⭕️ (오버헤드가 크다는 단점이 있음)</li><li>다양한 커스텀마이징 (자동 재연결, 네임스페이스, 룸관리)</li></ul><p>➡️ 다양한 사람들에게 동시에 메시지를 보낼 수 있으며, fallback 가능해서 <strong>채팅</strong> 기능에 <strong>적합하다.</strong></p><blockquote><strong>socket.io ↔️ nest사용하기 위해서는 GateWay를 왜 사용해야 하는가?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxHrPYCEg3RcTjuaUDU-Hg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TavF6T2Okbb72s14kSmoqA.png" /></figure><p>NestJs와 Socket.io를 연결해서 사용하기 위해서는 Gateway를 사용해서 작성해야 한다. GateWay는 서버와 클라이언트의 통신을 관리하는 역활을 하고 있다. 마치 다른 코드에서의 <strong>Controller</strong>같은 느낌이다.</p><blockquote>Socket.io 기본 코드</blockquote><pre>// 게이트워이 정의. 특정 포트 사용 설정, CORS 설정 추가 도메인에서 연결 가능<br>@WebSocketGateway(포트번호, {<br>  namespace: &#39;chat&#39;,<br>  cors: { origin: &#39;*&#39; },<br>})<br><br>export class EventsGateway<br>  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect<br>{<br>  constructor() {}<br>  <br>// 서버 인스턴스 생성. 서버 ➡️ 클라이언트 에게 데이터 전송 <br>  @WebSocketServer() server: Server;<br>  private logger: Logger = new Logger(&#39;EventsGateway&#39;);<br><br>  @SubscribeMessage(&#39;events&#39;)<br>// 클라이언트 (envent 라는 메세지 전송) ➡️ 서버 처리, 클라이언트에게 데이터 반환.<br>  handleEvent(@MessageBody() data: string): string {<br>    return data;<br>  }<br><br>// webSocket 서버가 초기화 되었을 때 로그 <br>  afterInit(server: Server) {<br>    this.logger.log(&#39;웹소켓 서버 초기화 ✅&#39;);<br>  }<br><br>// 클라이언트가 연결이 끊겼을 때 로그 기록<br>  handleDisconnect(client: Socket) {<br>    this.logger.log(`Client Disconnected : ${client.id}`);<br>  }<br><br>// 클리이언트가 연결됨녀 로그 기록<br>  handleConnection(client: Socket, ...args: any[]) {<br>    this.logger.log(`Client Connected : ${client.id}`);<br>  }<br>}</pre><p>저는 여기에 실시간 메세지 전송 코드를 추가하고 싶다. Socket.io의 장점은 <strong>다양한 커스텀마이징</strong> 할 수 있고 <strong>boardcast</strong> 가능하다. 그래서 <strong>boardcast</strong> 사용하면서 <strong>실시간 메세지 전송 </strong>코드 넣어볼려고 한다.</p><blockquote>실시간 메세지 전송 추가 된 socket.io 코드</blockquote><pre>// 메세지를 모든 연결된 클라이언트에게 브로드캐스트하는 기능 제공<br>broadcastMessage(event: string, message: any) {<br>    this.logger.log(`Broadcasting message: ${JSON.stringify(message)}`);<br>// 연결된 클라이언트에게 이벤트와 메세지 전송<br>    this.server.emit(event, message);<br>  }<br><br>// 단순 메세지 로그. 메세지가 잘 출력 되는 지 확인하기 위한 용도.<br>  log(message: string) {<br>    this.logger.log(message);<br>  }<br><br>// 실시간 메세지 보내는 로직. ChatRoomService에서 메세지 처리<br>  @SubscribeMessage(&#39;sendMessage&#39;)<br>  async sendMessage(<br>    client: Socket,<br>    message: { content: string; userId: number; nickname: string },<br>  ): Promise&lt;void&gt; {<br>    const { chatRoomId } = client.data;<br><br>    await this.chatRoomService.sendMessage(<br>      chatRoomId,<br>      message.userId,<br>      message.content,<br>      message.nickname,<br>    );<br><br>// 메세지 처리 된 후, 서버에서 boarcastMessage를 호출하여 모든 클라이언트에게 브로드캐스트 함.<br>// 모든 클라이언트가 실시간으로 새로운 메세지를 받을 수 있음<br>// 실시간 메세지 생성<br>  this.broadcastMessage(&#39;newMessage&#39;, message);<br>}</pre><p>기본 코드 아래에 추가 했다. 코드의 흐름도를 살펴보면</p><ol><li>클라이언트가 메세지를 서버로 전송 (sendMessage 이벤트 발생)</li><li>서버로 전송하면 메세지를 ChatRoomService 에 필요한 정보 포함해서 전송</li><li>처리된 메세지를 다시 모든 클라이언트에게 브로드 캐스트(실시간 메세지)</li></ol><p>클리이언트 ➡️ 서버(ChatRoomService 필요한 정보 전송) ➡️ 클라이언트(브로드캐스트)</p><blockquote>관계성 파악</blockquote><p>실시간 채팅을 구현한 걸 보면, <strong>“</strong><strong>ChatRoomService 에 메세지 정보를 왜 보내는 걸까?”</strong> , <strong>“왜 </strong><strong>socket.io는 </strong><strong>chatRoom 의 관계성이 뭐길래?&quot;, “ 메세지 저장은 어디에 할까?” </strong>라는 질문이 생길 수 있습니다. 이 둘의 관계를 이해하려면 ChatRoom 과 Sokcet.io 가 어떻게 상호작용하는지, 메세지 저장할 Message Entity를 왜 만들어야 하는지에 대해서 알아야 한다.</p><h4>ChatRoom 과 Message Entity</h4><p>chatRoom은 <strong>채팅방의 정보를 관리</strong>하고, Message는 <strong>그 방에서 주고받는 대화를 기록</strong>한다. 채팅방의 정보를 관리하는 곳에 메세지 주고 받는 대화를 기록한다면 메세지 기록이 많이 쌓일수록 chatRoom은 지나치게 복합하고 관리가 어려워진다. 그래서 따로 Message라는 Entity를 만드는 것이다.</p><p>chatRoom.entity.ts(채팅방의 정보를 관리)</p><pre>@Entity(&#39;chat_room&#39;)<br>export class ChatRoom extends TimeStamp {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column({ name: &#39;chat_name&#39;, type: &#39;varchar&#39;, length: 100, nullable: false })<br>  chat_name: string; // 채팅방 이름<br><br>  @OneToMany(() =&gt; Message, (message) =&gt; message.chatRoom)<br>  messages: Message[]; // 해당 채팅방에 속한 메시지들<br>}</pre><h4>chatRoom이 Message 관리하는 이유</h4><p>ChatRoom 엔티티는 채팅방의 이름(chat_name) 과 해당 채팅방에서 오가는 모든 메세지(message)를 관리합니다. Message배열을 통해 방에서 주고 받은 모든 메세지를 조회할 수 있습니다. @OneToMany 관계를 통해1:N 관계를 가지며 ChatRoom은 여러 개의 Message를 가져옵니다. message.chatRoom 을 통해 Message 엔티티 에서는 @ManyToOne 을 할 수 있게 관계를 만들어 줍니다.</p><p>Message.entity.ts(방에서 주고 받는 대화 기록)</p><pre>@Entity(&#39;message&#39;)<br>export class Message extends TimeStamp {<br>  @PrimaryGeneratedColumn()<br>  id: number; // 메시지 ID<br><br>  @Column({ type: &#39;text&#39;, nullable: false })<br>  content: string; // 메시지 내용<br><br>  @ManyToOne(() =&gt; ChatRoom, (chatRoom) =&gt; chatRoom.messages, { nullable: false })<br>  chatRoom: ChatRoom; // 메시지가 속한 채팅방<br><br>  @ManyToOne(() =&gt; User, (user) =&gt; user.messages, { nullable: false })<br>  user: User; // 메시지를 보낸 사용자<br>}</pre><p>Message 엔티티는 각 채팅방에서 주고받는 개발 대화 기록을 관리하는 역활을 합니다. 위에서 ChatRoom 엔티티가 @OneToMany 관계를 사용하여 Message 엔티티는 그 반대인 @ManyToOne 을 사용하여 관계를 설정해준다. 그리고 User 엔티티와도 관계 설정 해준다.</p><blockquote>ChatRoom ↔️ sockek.io</blockquote><p>socket.io 에서 나왔던 코드 await this.chatRoomService.sendMessage 이 코드 보면 chatRoomService 안에 sendMessage 로직을 가지고 온다.</p><pre>constructor(<br>    @InjectRepository(ChatRoom)<br>    private readonly chatRoomRepository: Repository&lt;ChatRoom&gt;,<br>    @InjectRepository(Message)<br>    private readonly messageRepository: Repository&lt;Message&gt;,<br>    @Inject(forwardRef(() =&gt; EventsGateway))<br>    private readonly eventsGateway: EventsGateway,<br>  ) {}<br><br>    .<br>    .<br>    .<br><br>async sendMessage(<br>    chatRoomId: number,<br>    userId: number,<br>    content: string,<br>    username: string,<br>  ): Promise&lt;Message&gt; {<br>    const chatRoom = await this.chatRoomRepository.findOne({<br>      where: { id: chatRoomId },<br>    });<br>    if (!chatRoom) {<br>      throw new NotFoundException(&#39;채팅방을 찾을 수 없습니다.&#39;);<br>    }<br><br>    const user = await this.userRepository.findOne({ where: { id: userId } });<br>    if (!user) {<br>      throw new NotFoundException(&#39;사용자를 찾을 수 없습니다.&#39;);<br>    }<br><br>    const message = this.messageRepository.create({<br>      content: content,<br>      nickname: username,<br>      chatRoom: chatRoom,<br>      user: user,<br>    });<br><br>    await this.messageRepository.save(message);<br><br>    // 실시간 메시지 전송<br>    this.eventsGateway.broadcastMessage(&#39;broadcastMessage&#39;, {<br>      chatRoomId: chatRoomId,<br>      content: message.content,<br>      nickName: username,<br>    });<br><br>    this.logger.log(<br>      `채팅방 ${chatRoomId}에 메시지 전송: ${message.content} by ${username}`,<br>    );<br><br>    return message;<br>  }</pre><h4>forwardRef(()) 를 쓰는 이유 -&gt; 의존성 문제 해결</h4><p>Moudule-A 에 있는 Service-A ↔️ Moudule-B에 있는 Service-B가 서로 의존 주입을 하려 하면 문제가 발생한다. 이를 해결하기 위해서는 forwardRef(()) 를 사용하는 것이다. <strong>Moudule에서도 써줘야하지만 </strong><strong>Service에서도 써줘야</strong> 한다. 그래서 service 코드에도 forewardRef(())를 넣어줘서 의존성 문제를 해결해 준다.</p><h4>메세지 처리의 분리와 확장성</h4><ul><li>메세지 전송과 저장을 분리해 실시간 성능과 데이터 영속성을 동시에 확보한다.</li><li>메세지를 Message 엔티티로 생성 후 messageRepository에 저장하여 데이터 영속성을 확보한다. 메시지 기록을 유지 할 수 있다.</li></ul><h4>실시간 메세지 전송의 비동기 처리</h4><ul><li>실시간 전송은 EventGateway의 broadcastMessage 를 통해 이루어진다.</li><li>Socket.IO 의 server.emit 사용하여 모든 클라이언트에 메세지를 브로드캐스트 하고, 클라이언트는 즉각적으로 수신된 메시지를 화면에 반영한다.</li><li>forwardRef()로 의존성 순환 문제 처리하고, 이를 통해 실시간 전송과 데이터 저장은 서로 다른 계층에서 독립적으로 처리할 수 있다.</li></ul><blockquote>소감</blockquote><p>이전에 long polling을 사용해 본 경험이 있어서, 실시간 전달 방식이 socket의 브로드캐스트와 유사하다고 느꼈습니다. 그러나 이번에 socket을 활용하면서, long polling과는 다른 방식으로 실시간 기능이 구현되는 것을 경험하며 더욱 깊이 이해할 수 있었습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a67e3f894e76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[실시간 채팅: Websocket 와 Socket.IO의 역활]]></title>
            <link>https://medium.com/@kawy.sojung/%EC%8B%A4%EC%8B%9C%EA%B0%84-%EC%B1%84%ED%8C%85-websocket-%EC%99%80-socket-io%EC%9D%98-%EC%97%AD%ED%99%9C-afad9e368698?source=rss-48475f033e55------2</link>
            <guid isPermaLink="false">https://medium.com/p/afad9e368698</guid>
            <category><![CDATA[handshake]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[difference]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[tcp-ip]]></category>
            <dc:creator><![CDATA[완두콩]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 06:56:09 GMT</pubDate>
            <atom:updated>2024-07-27T07:57:39.568Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yASI8HWmxTPeH9OOELW4uA.png" /><figcaption>socket vs websocket</figcaption></figure><p>‘소모임 및 친구 찾기 앱’ 관련된 팀 프로젝트를 만들고 있던 중, <strong>실시간 채팅</strong>에 대해서 이야기 한 적이 있습니다. 다양한 방식으로 실시간성 채팅을 만들 수 있지만, 몇 가지 요구사항이 있었습니다.</p><ul><li>실시간으로 <strong>양방향 통신</strong>이 되어야 한다</li><li>지속적인 연결을 통해 <strong>중단 없이</strong> 통신 보장 되어야 한다</li></ul><p>이러한 요구사항을 충족시키기 위해서는 <strong>Websocket</strong>와 <strong>Socket.Io</strong>를 검토하게 되었습니다.</p><h3>🤫 Socket.IO 와 WebSocket 같은 말 아니야?</h3><p>Socket.IO 는 웹 소켓을 활용한 라이브러리 일 뿐이다. Socket.IO를 사용하기 위해서는 먼저 기반 기술인<strong> Websocket</strong>을 먼저 알아야 한다.</p><h3>🤫WebSocket이 뭘까?</h3><ul><li>TCP/IP 통신 방식으로 실시간 양뱡향 데이터 전송을 위한 기술</li><li>TCP/IP 핸드쉐이킹과 유사한 Websocket 핸드쉐이킹</li><li>브라우저<strong> “나 웹소켓 이용할고야!😤”</strong> 라고 서버에게 알려주고, 서버가 <strong>“알겠어. 이제 이용해🙂‍↕️&quot; </strong>응답해주는 과정</li><li>HTTP 대신 WS 라는 프로토콜 사용</li></ul><blockquote><strong>📢TCP/IP..?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SILaT0xxGMI9NICFGLnoRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*1WmAFfUi13jNhmZNvPn0HA.png" /><figcaption>3-handshake:연결설정 와 4-handshake: 연결해제</figcaption></figure><p>TCP: 인터넷 상에서 <strong>데이터를 메세지 형태</strong>로 보내기 위해 IP와 함께 사용하는 프로토콜. <strong>연속성&lt; 신뢰성</strong> 있는 전송이 중요할 때 사용하는 프로토콜. <strong>연결지향 방식</strong>을 가지고 있다. 즉, 송신자가 수진자에게 IP 주소를 사용하여 데이터를 전달하고 그 데이터가 제대로 갔는지! 너무 빠르게 갔지는 않았는지 ! 제대로 받았다고 연락은 오는지! 대한 이야기</p><blockquote><strong>✨WebSocket 생긴 계기✨</strong></blockquote><p>Polling(폴링) <strong>단반향 통신</strong>으로 주기적으로 서버에 새로운 업데이트가 있는지 확인하는 요청을 보낸 후, 있으면 새로운 내용을 가져오는 1차적인 방식으로 그동안 해왔음. HTML 생긴 후 <strong>지속적인 양방향 통신 </strong>웹소켓이 생겼다.</p><ul><li>계속 연결된 상태 ➡ 업데이트 요청 보낼 필요 ❌. 서버에서 바로 클라이언트에게 알림</li><li>HTTP 프로토콜과 포트를 공유할 수 있어서 다른 포트 연결 필요성 ❌</li></ul><p>➡️ Polling보다 성능도 매우 개선됨</p><p>➡️ 각 브라우저마다 구현 방법이 달라 개발 어려우니까 표준 하나 만들자</p><blockquote><strong>✨WebSocket의 특징(독립적 성향)✨</strong></blockquote><ul><li>요청-응답 관계 방식(Polling)보다는 더 쉽고 자유롭게 데이터 교환 가능</li><li>80 포트를 통해 웹 서버에 연결</li><li>ws:// 시작하여 Streaming과 유사한 방식으로 푸쉬를 지원</li></ul><blockquote><strong>👍Websocket 장점👍</strong></blockquote><ul><li>HTML 웹 표준 기술이여서 별도의 모듈을 설치할 필요 없음</li><li>80포트 접속해서 추가로 방화벽 열지 않고도 양방향 통신 가능</li><li>낮은 오버헤드와 높은 성능 제공하여 데이터 크기가 크거나, 데이터 전송량이 많은 경우에는 더 저렴하고 빠르게 데이터 전송해줌</li></ul><blockquote><strong>🥺Websocket 단점🥺</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*kle6iCIonmsZOBSRLuE1MQ.png" /><figcaption>브로드캐스팅 그림으로 설명(위키백과 그림)</figcaption></figure><ul><li><strong>브로드 캐스팅(연결된 모든 사용자에게 메세지를 보내는 것)</strong> ❌</li></ul><p>브로드 캐스팅 없어서 여러 클라이언트에게 동시에 메시지를 보낼 때 각 연을 통해서 <strong>개별적으로</strong> 해야함. 사용자가 ⬆️ 과부하가 걸림</p><ul><li><strong>fallback 옵션 ❌</strong></li></ul><p>통신 연결되지 않았을 경우 대비 옵션을 주지 않음. 연결되지 않으면 자동 복구를 시도하지 않음.</p><blockquote>✏️결론</blockquote><p><strong>가상화폐 거래소 </strong>같이 데이터 전송이 많은 경우에는 빠르고 비용이 적은 표준 Websocket 이용이 바람직하다. 채팅 관련 기능에는 브로드 캐스팅 안되고 , fallback 옵션이 안되는 걸로 Websocket은 바람직하지 않음.</p><h3>✨Socket.io 탄생(포괄적인 성향)✨</h3><p>Websocket은 오래된 버전의 웹 브로우저에서는 지원이 안되는 문제가 있다. 다양한 방식의 실시간 웹 기술을 손 쉽게 사용할 수 있는 모듈을 만들었다. (websocket 단점을 보안해서 나온 기술)</p><blockquote>👍Socket.io 장점👍</blockquote><ul><li>브로드 캐스팅 ⭕️</li></ul><p>서버에서 여러 클라이언트에게 동시에 메세지를 보낼 때 각 연결을 개별적으로 하지 않고 단 하나의 연결만으로 여러 작업을 처리. 접속한 사용자 모두에게 메세지를 전송 할 수 있음. WS보다 과부하가 덜 함.</p><ul><li>fallback 옵션 ⭕️</li></ul><p>개발자가 지정한 연결 방식에 따라 자동으로 재연결 시도. 연결하기 전에 대기 시간, 시도 횟수 등을 설정할 수 있다.</p><blockquote>🥺Socket.io 단점🥺</blockquote><ul><li>fallback 옵션으로 인해 웹소켓보다 오버헤드가 더 크다.</li><li>socket의 장점인 <strong>다양한 커스텀마이징</strong> 으로 인한 추가 기능을 제공하기 위해, 메타데이터와 제어 정보 제공(자동 재연결, 네임스페이스, 룸관리) 로 인해 성능이 weboscket보다는 떨어진다.</li><li>브로드캐스팅으로 인해 동시에 많은 연결을 해야 해서 서버에 부하를 줄 수 있다.</li></ul><p>➡️ <strong>“성능은 개선하면 되는 거 아니야?”</strong> 라고 생각할 수도 있다. 맞다. 성능은 <strong>redis와 같은 성능 개선 도구</strong>를 추가적으로 사용하여 성능을 개선할 수 있다. 하지만 귀찮을 수도 있다.</p><blockquote>✏️결론</blockquote><p>다양한 사람들에게 동시에 메시지를 보낼 수 있으며, fallback 가능해서 <strong>채팅</strong> 기능에 <strong>적합하다</strong>. 하지만 데이터가 크고, 빠르게 데이터를 이동해야 하는 가상화폐 거래소에서는 부적합하다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afad9e368698" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multer(multipart/formdata) + ExpressJs 이미지 업로드]]></title>
            <link>https://medium.com/@kawy.sojung/multer-multipart-formdata-expressjs-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EC%97%85%EB%A1%9C%EB%93%9C-13e00746cee7?source=rss-48475f033e55------2</link>
            <guid isPermaLink="false">https://medium.com/p/13e00746cee7</guid>
            <category><![CDATA[muti]]></category>
            <category><![CDATA[multer]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[multipart-form-data]]></category>
            <category><![CDATA[surveys]]></category>
            <dc:creator><![CDATA[완두콩]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 09:11:41 GMT</pubDate>
            <atom:updated>2024-03-02T09:15:40.340Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>왜 Mutipart/formdata 썼는가?</strong></blockquote><p>이번 부트캠프를 할 때 ‘<strong>설문지 커스텀마이징 서비스</strong>&#39;를 만들었다.</p><p>설문지 생성 api 를 만들 때 하나의 요청에서 설문 데이터와 같은 JSON 형식의 텍스트 정보와 이미지 파일을 동시에 서버에 전송 할 수 있다.</p><blockquote><strong>간단하게 설명하면</strong></blockquote><ul><li>설문지 커스텀 마이징 서비스 개발</li><li>설문 생성 api ➡️ <strong>Json 데이터(텍스트 필드) + 이미지 </strong>동시 업로드</li><li>Node(Express.js) 사용할 것</li></ul><p>➡️ multer 미들웨어 사용. 멀티파트(form-data) 요청을 쉽게 처리할 수 있음.</p><blockquote><strong>multer?</strong></blockquote><ul><li><strong>유연한 파일 처리 옵션</strong> : multer 는 메모리 파일 저장하는 방식부터, 디스크 직접 저장, 클라우드 스토리지 같은 외부 저장소에 저장하는 방식을 제공한다.</li><li><strong>자동 멀티파트 분석</strong> : multer 는 자동으로 분석하여 이미지 파일과 텍스트 파일를 적절히 분리해준다. 개발자는 req.body 통해 텍스트 파일에 접근, req.files 통해 이미지 파일 정보에 접근할 수 있다.</li><li><strong>파일 업로드 처리</strong> : 파일을 안전하게 서버에 저장할 수 있으며, 저장 전에 파일 이름 변경, 특정 폴더 저장하는 등의 처리를 가능하다.</li></ul><p>뒤에 적절하게 3가지를 사용하는 방법을 자세히 이야기 해 볼 예정이다.</p><blockquote><strong>multer 설치 방법</strong></blockquote><pre>npm i multer<br>   or<br>npm install multer</pre><pre>// s3를 사용한다면<br>npm install @aws-sdk/client-s3<br>npm install multer-s3</pre><p>multer 사용하기 전에 설문지 생성 api 만들어 볼 예정이다.</p><blockquote><strong>설문지 생성 api</strong></blockquote><p>설문지 생성 이해하기 위해서는 erd를 먼저 보는 게 좋을 것 같다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fZVFMOyNoLZJYHQI_msLA.png" /><figcaption>설문지 생성 erd</figcaption></figure><p><strong>Survey는 여러 </strong><strong>Question을 포함하는 설문지이며, 각 </strong><strong>Question은 다수의 </strong><strong>Choice를 가진 질문</strong></p><p>전달받는 설문 데이터 (surveyData)를 기반으로 새로운 설문지 (Survey), 관련 질문들(Question), 그리고 각 질문의 선택지(Choice)를 데이터베이스에 생성한다.</p><pre>const { sequelize } = require(&#39;../models&#39;);<br>const { Survey, Question, Choice } = require(&#39;../models&#39;);<br><br>const createSurveyWithQuestionsAndChoices = async (surveyData, res) =&gt; {<br>  const t = await sequelize.transaction();</pre><ul><li>Sequelize ORM을 사용함</li><li>Survey ,Question ,Choice 테이블 가지고 와서 안에 있는 필드 사용함</li></ul><p><strong>transcation 쓰는 이유</strong></p><ul><li>데이터베이스의 상태를 변화시키는 하나 이상의 연산들을 묶어서, 모든 연산이 완전히 성공하거나, 하나라도 실패할 경우 모든 작업이 취소되도록(롤백되도록) 보장하는 것 말함</li><li>Sequelize ORM을 사용하는 Node.js 환경에서 트랜잭션을 시작하는 명령</li></ul><pre>const { sequelize } = require(&#39;../models&#39;);<br>const { Survey, Question, Choice } = require(&#39;../models&#39;);<br><br>const createSurveyWithQuestionsAndChoices = async (surveyData, res) =&gt; {<br>  const t = await sequelize.transaction();<br><br>  try {<br>    console.log(&#39;Received survey data:&#39;, surveyData);<br><br>    const {<br>      userId,<br>      title,<br>      description,<br>      open,<br>      font,<br>      color,<br>      buttonStyle,<br>      deadline,<br>      questions,<br>      mainImageUrl, // 메인 이미지 URL<br>    } = surveyData;<br><br>    console.log(&#39;요청 본문 수신:&#39;, surveyData);<br><br>    const surveyUrl = `http://yourwebsite.com/survey/placeholder`;</pre><p><strong>surveyData 를 먼저 하는 이유</strong></p><ul><li>클라이언트로부터 받은 데이터를 데이터베이스 저장 하기 전에 구조화하고 검증하는 과정이 필요하기 때문</li><li>전송된 데이터가 올바른 형식을 갖추었는지 확인</li><li>필요한 모든 정보를 포함하고 있는지 확인</li><li>데이터베이스에 저장하기 적합한 상태 만들어줌</li></ul><p>➡️ 클리이언트에게 어떤 형식으로 데이터를 보낼 것인지 명시함.</p><pre>const survey = await Survey.create(<br>      {<br>        userId,<br>        title,<br>        description,<br>        open,<br>        url: surveyUrl,<br>        font,<br>        color,<br>        buttonStyle,<br>        mainImageUrl,<br>        deadline,<br>      },<br>      { transaction: t },<br>    );<br><br>    const surveyId = survey.id;<br>    const updatedSurveyUrl = `http://yourwebsite.com/survey/${surveyId}`;<br><br>    await Survey.update(<br>      { url: updatedSurveyUrl },<br>      {<br>        where: { id: surveyId },<br>        transaction: t,<br>      },<br>    );</pre><p><strong>Survey 필드를 사용하여 설문 survey 생성</strong></p><ul><li>JSON 구조에서 설문 데이터를 survey 키로 묶어 제공함. 데이터의 구조와 목정을 명확히 처리하여 간소화 해줌.</li><li>surveyData 형식을 맞춰 survey필드에 데이터 생성</li><li>만약 surveyData 형식과 맞다면 트랜잭션을 사용해 저장</li><li>url은 클라이언트가 작성 안해줘도 됨. 이미 api에서 작성해 줌</li><li>survey 필드 생성되고 고유 ID ( surveyId )가 할당됨. ID는 연관된 질문들을 생성하는데 사용됨. Question 는 surveyId 를 사용하여 특정 설문지에 소속됨</li></ul><p>➡️ 설문 생성 시, 초기 URL 설정하고 설문지에 고유ID (surveyId)를 할당</p><p>➡️ surveyId 를 활용해, 연관된 질문(Question)들을 특정 설문지에 소속되도록 생성</p><pre><br>for (const question of questions) {<br>      if (<br>        ![<br>          &#39;MULTIPLE_CHOICE&#39;,<br>          &#39;SUBJECTIVE_QUESTION&#39;,<br>          &#39;CHECKBOX&#39;,<br>          &#39;DROPDOWN&#39;,<br>        ].includes(question.type)<br>      ) {<br>        throw new Error(&#39;Invalid question type&#39;);<br>      }<br><br>      const questionImageUrl = question.imageUrl;<br><br>      const newQuestion = await Question.create(<br>        {<br>          surveyId,<br>          type: question.type,<br>          content: question.content,<br>          imageUrl: questionImageUrl, <br>        },<br>        { transaction: t },<br>      );<br><br>      console.log(`questionId: ${newQuestion.id}`);</pre><p><strong>Question 필드를 사용하여 각 설문의 quesiton 생성</strong></p><ul><li>여러 개의 question 묶인 게 questions 임. 그래서 JSON 구조에서 설문 데이터를 questions 키로 묶어 제공함. surveyData 형식에서 questions 으로 작성해서 형식에 맞게 만듬 (만약surveyData 형식 변경이 된다면 questions 변수 이름 변경해줘야함)</li><li>question의 type이 4개 중 한 개가 아니면 error</li><li>newQuestion은 question 필드에 질문 데이터 저장</li><li>transcation를 이용해 저장</li><li>question 필드가 생성되고 고유ID (questionId)가 할당됨. questionId를 활용하여 선택지(chocie)을 생성</li></ul><p>➡️ 질문 생성 시, 고유ID (questionId)가 할당</p><p>➡️ 각 질문에 할당된 고유 ID(questionId)를 이용해, 관련 선택지(choice)들을 구성</p><pre>if (question.choices &amp;&amp; question.choices.length &gt; 0) {<br>        for (const choice of question.choices) {<br>          await Choice.create(<br>            {<br>              questionId: newQuestion.id,<br>              option: choice.option,<br>            },<br>            { transaction: t },<br>          );<br>        }<br>      }<br>    }<br><br>    await t.commit();<br>    res.status(201).json({ message: &#39;설문 생성 완료&#39;, surveyId: surveyId });<br>  } catch (error) {<br>    await t.rollback();<br>    res.status(500).json({ message: &#39;설문 생성 오류&#39;, error: error.message });<br>  }<br>};<br><br>module.exports = { createSurveyWithQuestionsAndChoices };</pre><p><strong>Choice 필드를 사용하여 질문의 quesiton 생성</strong></p><ul><li>question.choice: 질문(question) 데이터에 선택지(choices)가 포함</li><li>question.choices.length : 선택지의 수가 0보다 큰지 확인</li></ul><p><em>클라이언트 ➡️ JSON문 작성 ➡️ 서버 ➡️ 선택지 존재 여부 검사</em></p><ul><li>questionsId 를 통해 고유 질문 안에 선택지를 생성해줄 수 있다.</li></ul><blockquote><strong>multer 사용하여 mutipart/form 만들어보기</strong></blockquote><pre>const storage = multer.memoryStorage(); // 파일을 메모리에 저장<br>const uploadMiddleware = multer({<br>  storage: storage,<br>  // 파일만 허용하도록 설정<br>  fileFilter: (req, file, cb) =&gt; {<br>    if (file.fieldname === &#39;survey&#39;) { // JSON문 key이름이 &#39;survey&#39; 시작하는지 확인<br>      cb(null, false); // JSON 데이터는 파일이 아닌 것으로 처리<br>    } else {<br>      cb(null, true); // 파일은 허용<br>    }<br>  },<br>});</pre><p><strong>multer 설정 및 초기화</strong></p><ul><li><strong>유연한 파일 처리 옵션</strong> : multer.memoryStorage() 를 사용하여 파일을 서버의 메모리에 임시로 저장하는 방식 선택. 메모리 파일 저장하는 방식부터, 디스크 직접 저장, 클라우드 스토리지 같은 외부 저장소(s3)에 저장하는 방식 3개 중에서 메모리 파일 저장 선택.</li></ul><p><strong>❓ S3랑 연동을 하는데 왜 클라우드 스토리지 쓰지 않은 이유 </strong>❓</p><ul><li>서버에서 파일을 처리하거나 검증를 위해</li><li>파일의 형식을 확인하고, 이미지 크기를 조정을 임시로 파일을 메모리에 저장</li><li>fileFilter 를 통해 파일 유형을 검증해 줌</li><li>메모리에 저장한 다음에 나중에 S3에 업로드 <strong>➡️ </strong>뒤에서 설명</li></ul><pre>router.post(<br>  &#39;/&#39;,<br>  uploadMiddleware.fields([<br>    { name: &#39;mainImageUrl&#39;, maxCount: 1 }, //mainImageUrl를 최대 1개 업로드 가능<br>    { name: &#39;imageUrl&#39;, maxCount: 10 }, // imageUrl을 최대 10개 업로드 가능<br>  ]),<br>  async (req, res) =&gt; {<br>    try {<br>      console.log(&#39;Request received on / endpoint.&#39;);<br>      console.log(&#39;req.body:&#39;, req.body);<br>      <br>      // req.body에서 survey 데이터가 있는지 확인<br>      if (!req.body.survey) {<br>        return res.status(400).json({ message: &#39;No survey data provided&#39; });<br>      }<br>     <br>      // JSON 문자열을 객체로 파싱. <br>      const parsedData = JSON.parse(req.body.survey);<br>      console.log(&#39;Parsed survey data:&#39;, parsedData);<br>      <br>      // 복잡한 데이터 구조에서 필요한 부분만을 선택적으로 추출<br>      // parseData에서 survey만 가지고 온다<br>      const surveyData = parsedData.survey;<br>      console.log(&#39;Extracted survey data:&#39;, surveyData);<br><br><br>      // 파싱된 설문 데이터에서 questions 필드가 배열인지 확인<br>      if (!Array.isArray(surveyData.questions)) {<br>        console.log(&#39;No questions array in surveyData&#39;);<br>        return res<br>          .status(400)<br>          .json({ message: &#39;Invalid survey data: No questions array&#39; });<br>      }<br><br>      // 이미지들이 있는지 확인하고 s3 업로드<br>      if (req.files[&#39;mainImageUrl&#39;] &amp;&amp; req.files[&#39;mainImageUrl&#39;][0]) {<br>        surveyData.mainImageUrl = await uploadFileToS3(<br>          req.files[&#39;mainImageUrl&#39;][0],<br>        );<br>      }<br><br>      const imageUploadPromises = surveyData.questions.map(<br>        async (question, index) =&gt; {<br>          // 클라이언트에서 &#39;imageUrl[]&#39;의 배열 형태로 이미지를 보냈다고 가정<br>          if (req.files[&#39;imageUrl&#39;] &amp;&amp; req.files[&#39;imageUrl&#39;][index]) {<br>            const file = req.files[&#39;imageUrl&#39;][index];<br>            question.imageUrl = await uploadFileToS3(file);<br>          }<br>          return Promise.resolve();<br>        },<br>      );<br><br>      // 모든 이미지 업로드가 완료되기를 기다립니다.<br>      await Promise.all(imageUploadPromises);<br><br>      // 설문 생성 로직 호출<br>      await surveyController.createSurveyWithQuestionsAndChoices(<br>        parsedData.survey, <br>        res,<br>      );<br>    } catch (error) {<br>      console.error(&#39;Error processing request:&#39;, error);<br>      res.status(400).json({<br>        message: &#39;Error processing survey data&#39;,<br>        error: error.message,<br>      });<br>    }<br>  },<br>);</pre><p><strong>multer 이용해 mutipart/form 사용</strong></p><ul><li><strong>자동 멀티파트 분석</strong> : req.files 를 통해 이미지 파일을 처리함. 메인 이미지(mainImageUrl)와 질문이미지 파일(imageUrl)들에 접근함. req.body.survey를 통해 텍스트 데이터에 접근함.</li><li><strong>AWS S3 업로드</strong>: multer 를 통해 메모리에 임시 저장된 파일들을 검증을 거쳐, 안전하게 S3로 업로드 해줌.</li></ul><blockquote><strong>multer-s3 사용하여 s3 이용</strong></blockquote><pre>const {<br>  S3Client,<br>  PutObjectCommand,<br>  DeleteObjectCommand,<br>} = require(&#39;@aws-sdk/client-s3&#39;);<br>const multer = require(&#39;multer&#39;);<br>const multerS3 = require(&#39;multer-s3&#39;);<br>const path = require(&#39;path&#39;);<br>// 여기 있는 파일 형식만 업로드 가능<br>const allowedExtensions = [&#39;.png&#39;, &#39;.jpg&#39;, &#39;.jpeg&#39;, &#39;.bmp&#39;, &#39;.gif&#39;];<br><br>// AWS S3 클라이언트 설정<br>const s3Client = new S3Client({<br>  region: process.env.AWS_S3_REGION,<br>  credentials: {<br>    accessKeyId: process.env.AWS_S3_ACCESS_KEY,<br>    secretAccessKey: process.env.AWS_S3_SECRET_KEY,<br>  },<br>});<br><br>async function uploadFileToS3(file) {<br>  // 현재 시간의 타임스탬프<br>  const timestamp = Date.now();<br>  // 특정 폴더에 저장<br>  const filename = `uploads/survey-images/${timestamp}_${file.originalname}`;<br><br>  const params = {<br>    Bucket: process.env.AWS_BUCKET,<br>    Key: filename,<br>    Body: file.buffer,<br>    ACL: &#39;public-read-write&#39;,<br>    ContentType: file.mimetype,<br>  };<br><br>  try {<br>    const command = new PutObjectCommand(params);<br>    await s3Client.send(command);<br>    // s3 업로드 완료 후 URL 반환<br>    return `https://${process.env.AWS_BUCKET}.s3.${process.env.AWS_S3_REGION}.amazonaws.com/${filename}`;<br>  } catch (error) {<br>    console.error(&#39;Error uploading file to S3:&#39;, error);<br>    throw error;<br>  }<br>}<br><br>module.exports = { uploadS3, uploadFileToS3 };</pre><p><strong>multer 이용해 s3 업로드</strong></p><ul><li><strong>파일 업로드 처리</strong></li></ul><blockquote><strong>예제</strong></blockquote><p><strong>JSON문 예시</strong></p><pre>{<br>  &quot;survey&quot;: {<br>    &quot;userId&quot;: 1,<br>    &quot;title&quot;: &quot;행복 설문조사&quot;,<br>    &quot;description&quot;: &quot;행복합니다&quot;,<br>    &quot;open&quot;: true,<br>    &quot;font&quot;: &quot;happy_font&quot;,<br>    &quot;color&quot;: &quot;#0808080&quot;,<br>    &quot;buttonStyle&quot;: &quot;round&quot;,<br>    &quot;mainImageUrl&quot;: &quot; &quot;,<br>    &quot;deadline&quot;: &quot;2023.05.31 03:03:14&quot;,<br>    &quot;questions&quot;: [<br>        {<br>            &quot;type&quot;: &quot;CHECKBOX&quot;,<br>            &quot;content&quot;: &quot;행복도를 선택하세요.&quot;,<br>            &quot;imageUrl&quot;: &quot; &quot; ,<br>            &quot;choices&quot;: [<br>                {&quot;option&quot;: &quot;행복1&quot;},<br>                {&quot;option&quot;: &quot;행복2&quot;},<br>                {&quot;option&quot;: &quot;행복3&quot;}<br>            ]<br>        },<br>        {<br>            &quot;type&quot;: &quot;SUBJECTIVE_QUESTION&quot;,<br>            &quot;content&quot;: &quot;1번에서 선택한 사탕이 좋아하는 이유를 작성하세요.&quot;,<br>            &quot;imageUrl&quot;: &quot; &quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;MULTIPLE_CHOICE&quot;,<br>            &quot;content&quot;: &quot;가장 선호하는 여가 활동은 무엇인가요?&quot;,<br>            &quot;choices&quot;: [<br>                {&quot;option&quot;: &quot;영화 보기&quot;},<br>                {&quot;option&quot;: &quot;독서&quot;},<br>                {&quot;option&quot;: &quot;운동&quot;}<br>            ],<br>            &quot;imageUrl&quot;: &quot; &quot;<br>          }<br>      ]<br>    }<br>}</pre><p><strong>Postman 으로 muti/form-data 보내기</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jDyG7n5GuIdD9YB-z9tlg.png" /><figcaption>muti/form-data 보내는 방법</figcaption></figure><ul><li>body ➡️ form-data ➡️ Text/File 선택 ➡️ value값에 json문 작성 or 사진 업로드</li><li><strong>JSON문</strong> : &#39;survey&#39;를 사용하여 데이터를 감싸 전송함. if(file.fieldname === ‘survey’) 를 통해 JSON 문 검증함.</li><li><strong>이미지</strong> : mainImageUrl , imageUrl 은 사전 약속된 키. 별도 정의 없이 사용되며 JSON문처럼 복잡성 검증 필요 없음.</li></ul><blockquote><strong>후기</strong></blockquote><p>처음에는 이걸 만들 수 있을까? 생각을 많이 했는데 많은 삽질과 많은 시간만 주면 못할 게 없다는 걸 알았다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13e00746cee7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS의 모든 것]]></title>
            <link>https://medium.com/@kawy.sojung/aws%EC%9D%98-%EB%AA%A8%EB%93%A0-%EA%B2%83-d90bc2f55b20?source=rss-48475f033e55------2</link>
            <guid isPermaLink="false">https://medium.com/p/d90bc2f55b20</guid>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[problems]]></category>
            <category><![CDATA[volume]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[완두콩]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 19:51:06 GMT</pubDate>
            <atom:updated>2024-02-18T19:59:13.051Z</atom:updated>
            <content:encoded><![CDATA[<p>처음 부트캠프를 했을 때에는 개발이 처음이라 aws까지는 하지 못해 아쉬웠다. 그래서 다음에 기회가 있다면 aws를 해보고 싶었다. 그래서 이번 두 번째 부트캠프에서 aws를 해볼 기회가 생겨 해보았다!</p><h3>루트 사용자 vs IAM사용자</h3><p>처음부터 고비였다. 루트 사용자와 IAM 사용자의 차이점을 알지 못했다. 그래서 뭐로 해야 할 지 몰랐다.</p><blockquote><strong>루트 사용자</strong></blockquote><ul><li>모든 권한을 가진 슈퍼 어드민 계정</li><li>계정의 모든 리소스에 대한 엑세스 권한 허용</li><li>보안에 취약함</li></ul><p>➡️ 계정이 털리면 요금 폭탄!</p><blockquote><strong>IAM 사용자</strong></blockquote><ul><li>이런 문제점을 보안해 준 계정</li><li>대부분 이 계정 쓰는 걸 추천!</li></ul><h3><strong>EC2 인스턴스 생성</strong></h3><p><a href="https://ziszini.tistory.com/136">[AWS] AWS EC2를 이용해 배포하기 (1) - EC2 인스턴스 생성 &amp; 접속하기 (SSH KEY 접속)</a></p><p>여기 있는 블로그 보면 쉽게 인스턴스 생성할 수 있음</p><p>⚠️여기서 주의해야 할 점⚠️</p><ul><li>ubutu server 22.04 ➡️ 20.04 추천 (너무 최신보다는 전 단계를 추천)</li><li>인스턴스 유형할 수 있다면 프리티어 버전이 좋지만 솔직히 무료 버전을 쓰려다가 넘 힘들어서 유료 버전으로 바꿨다. (바꾼 이유는 뒤에서 설명) 가격 비교해서 유료 버전 쓰는 게 정신적 건강에 좋다.</li><li>볼륨도 30보다는 60 추천하다. 이것도 정신적 건강을 위해 변경을 하는 게 좋다. 하지만 이건 나중에 변경해줄 수 있으므로 일단 30으로 해주는 것도 추천! (이 문제도 뒤에서 설명)</li></ul><h3><strong>SSH와 VScode 연동할 때 문제점</strong></h3><p><a href="https://bosungtea9416.tistory.com/entry/VScode%EB%A1%9C-%EC%84%9C%EB%B2%84%EC%97%90-SSH-%EC%9B%90%EA%B2%A9-%EC%A0%91%EC%86%8D%ED%95%98%EA%B8%B0">VScode로 서버에 SSH 원격 접속하기</a></p><p>처음에는 이 블로그가 많이 도움이 되었다.</p><blockquote><strong>.pem이 안열리는 문제</strong></blockquote><p>.pem안에 있는 파일을 나중에 필요해서 파일을 열려고 했는데 아래 사진과 같이 보이지가 않아서 파일 확인을 할 수 없었다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vspYMmDJntQYhD9WFMfjhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*LMmy9tqOGPb9ZN0RWAF78Q.png" /></figure><p>vscode 열어서 거기서 열면 되는 걸 몰라서 헤멨다. 그리고 생각보다 파일 안에 내용 쓸 때가 없다. ci/cd 만들 때 말고는 딱히 안에 내용을 쓴 적이 없는 것 같다.</p><blockquote><strong>Ec2 인스턴스 연결에서 ssh연결되는데 vscode에서만 안되는 문제</strong></blockquote><p><strong>그 전에 왜 ssh를 굳이 vscode와 연동해야 하는 이유</strong></p><ul><li>Ec2 인스턴스 연결에서 하면 파일 변경 및 파일 삭제가 귀찮아진다. ( vi명령어 작성하고 esc 눌러서 파일 변경하고 esc 눌르고 :wq해줘야함)</li><li>vscode에서는 파일 변경이 편해진다.</li></ul><p><strong>대부분 vscode 연동에 오류나는 이유</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i1qRKlGoH8Fzb-mQOsZiWg.png" /><figcaption>timeout 에러</figcaption></figure><ol><li>.pem에 권한 설정을 안해줬을 경우</li><li>user을 잘못 설정 했을 경우</li><li>HostName을 잘못 설정 했을 경우</li><li>그냥 안됨 (이럴 때에는 잠깐 쉬었다가 다시 하면 됨)</li></ol><blockquote><strong>.pem에 권한 설정을 안해줬을 경우</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0aTUBnlcyD9bzdQQDex2oA.png" /></figure><p>인스턴스 들어가서 ‘연결’ 버튼 누르면 인스턴스에 연결이 뜬다.</p><p>터미널에 들어가서 pem이 저장된 곳으로 간다. 간 다음에 ‘chmod 400 이름.pem’ 권한 설정을 해준다.</p><p>그리고 ‘예’에 있는 걸 쳐주면 터미널로도 ssh 열린다.</p><p>그 상태에서 다시 vscode와 ssh 연동을 하면 된다.</p><blockquote><strong>user을 잘못 설정 했을 경우</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*BYjyHaESjwZUMjM4bWobVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*5mzaqtdeNrKvUXu3DqCKZQ.png" /></figure><pre>Host [원하는 이름 작성]<br>    HostName [퍼블릭 IPv4 DNS]<br>    User [&#39;사용자 이름&#39; 그대로 작성]<br>    Port [22]<br>    IdentityFile [.pem 절대 경로]</pre><ul><li>user 이름을 사용자 이름에 있는 이름 적확히 작성해줘야 한다</li></ul><p>➡️ 대부분 config를 잘못 써줘서 생기는 일이다.</p><h3>vscode에서 코드 수정</h3><p>ssh에서 .env넣어줘야한다.</p><p>근데 ssh에서는 코드를 추가할려면 코드 작성해줘야 한다.</p><pre>sudo chown -R ubuntu(사용자 이름 작성) *</pre><p>현재 작업 중인 디렉토리의 모든 파일과 디렉토리의 소유권을 ubuntu사용자로 변경됩니다. 이것은 SSH를 통해 서버에 접속했을 때, 특정 사용자가 파일을 수정하거나 접근할 수 있게 하기 위해 사용될 수 있습니다.</p><h3>힙이 터진다?</h3><pre>&gt; [frontend 6/6] RUN npm run build:<br>2.363 <br>2.363 &gt; frontend@0.0.0 build<br>2.363 &gt; tsc &amp;&amp; vite build<br>2.363 <br>18.18 <br>18.18 &lt;--- Last few GCs ---&gt;<br>18.18 ) [17:0x7fefad5c7010]    14356 ms: Mark-sweep (reduce) 476.3 (486.2) -&gt; 475.9 (486.2) MB, 503.2 / 0.0 ms  (+ 4.4 ms in 3 steps since start of marking, biggest step 4.0 ms, walltime since start of marking 520 ms) (average mu = 0.161, current mu = 0.026) fina[17:0x7fefad5c7010]    15138 ms: Mark-sweep (reduce) 476.1 (486.2) -&gt; 476.1 (486.2) MB, 623.7 / 0.0 ms  (+ 4.9 ms in 3 steps since start of marking, biggest step 4.7 ms, walltime since start of marking 639 ms) (average mu = 0.180, current mu = 0.196) fina<br>18.18 <br>18.18 &lt;--- JS stacktrace ---&gt;<br>18.18 <br>18.18 FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory<br>19.06 Aborted (core dumped)<br>------<br>failed to solve: process &quot;/bin/sh -c npm run build&quot; did not complete successfully: exit code: 134</pre><p>자꾸 프론트에서 힙이 터진다</p><p><strong>터지는 이유?</strong></p><blockquote>package문이 너무 많으면 터진다.</blockquote><p>➡️ frontend에 있는 패키지에 쓸데없는 것들을 지워줘야 한다.</p><p>하지만 저희는 시간이 없어서 이렇게 하지 못했습니다.</p><blockquote>swap 메모리 부족해서 터진다.</blockquote><p>➡️ 인스턴스 유형을 높인다.</p><p>돈만 있다면 힙이 터질 때마다 인스턴스 유형 높여주는 것도 방법이긴 하지만 추천하지는 않는다. 저는 마지막으로 t3.large까지 갔다가 t3.medium으로 낮췄다.</p><p>➡️ swap 메모리를 더 넣어줌</p><p><a href="https://repost.aws/ko/knowledge-center/ec2-memory-swap-file">스왑 파일을 사용하여 Amazon EC2 인스턴스의 스왑 공간으로 메모리 할당</a></p><p>위에 있는 블로그 따라하면 swap 메모리를 4기가 늘릴 수 있다. 처음에는 swap 메모리 최대가 4기가인줄 알고 t3.medium으로 해고 swap 늘려줘도 힙이 터져서 t3.large까지 갔다. (이때도 swap은 최대 4기가인줄 알고 해줬는데도 터져서 멘붕이였다) 하지만, swap 메모리는 최대라는 표현이 없었다. t3.large에서 8기가로 늘어주고t3.medium으로 크기 변경해 주었다.(변경해줄려면 중지시키고 들어가서 상태 아래에 인스턴스 변경 눌러서 변경해줬다)</p><p>heap도 안터지고swap 메모리도 늘어나고 아주 좋다.</p><p>prometheus grafana 연동이 되어있다면 뭐가 어디가 문제인지 쉽게 찾을 수 있다.</p><pre>sudo dd if=/dev/zero of=/swapfile bs=128M count=16 (4G)<br><br>sudo dd if=/dev/zero of=/swapfile bs=128M count=64 (8G)<br><br># 이것만 바꾸고 다른 건 똑같이 해주면 된다</pre><h3>볼륨 부족</h3><pre>=&gt; ERROR [backend 4/6] RUN npm install                                16.7s<br>------<br> &gt; [backend 4/6] RUN npm install:<br>16.41 npm WARN tar TAR_ENTRY_ERROR ENOSPC: no space left on device, write<br>16.42 npm ERR! code ENOSPC<br>16.43 npm ERR! syscall write<br>16.43 npm ERR! errno -28<br>16.43 npm ERR! nospc ENOSPC: no space left on device, write<br>16.43 npm ERR! nospc There appears to be insufficient space on your system to finish.<br>16.43 npm ERR! nospc Clear up some disk space and try again.<br>16.45 <br>16.45 npm ERR! A complete log of this run can be found in: /root/.npm/_logs/2024-01-29T19_16_48_018Z-debug-0.log<br>------<br>failed to solve: process &quot;/bin/sh -c npm install&quot; did not complete successfully: exit code: 228</pre><p>“ENOSPC: no space left on device, write”는 시스템에 충분한 디스크 공간이 없어 npm install 명령을 완료할 수 없음을 나타냅니다.</p><pre>ubuntu@ip-172-31-20-50:~/project$ df -h<br>Filesystem       Size  Used Avail Use% Mounted on<br>/dev/root         29G   29G  9.8M 100% /<br>devtmpfs         1.9G     0  1.9G   0% /dev<br>tmpfs            1.9G  1.1M  1.9G   1% /dev/shm<br>tmpfs            386M  1.7M  384M   1% /run<br>tmpfs            5.0M     0  5.0M   0% /run/lock<br>tmpfs            1.9G     0  1.9G   0% /sys/fs/cgroup<br>/dev/loop0        25M   25M     0 100% /snap/amazon-ssm-agent/7628<br>/dev/loop2        56M   56M     0 100% /snap/core18/2812<br>/dev/loop1        56M   56M     0 100% /snap/core18/2790<br>/dev/loop3        64M   64M     0 100% /snap/core20/2015<br>/dev/loop4        64M   64M     0 100% /snap/core20/2105<br>/dev/loop5        92M   92M     0 100% /snap/lxd/24061<br>/dev/loop6        41M   41M     0 100% /snap/snapd/20671<br>/dev/loop7        41M   41M     0 100% /snap/snapd/20290<br>/dev/nvme0n1p15  105M  6.1M   99M   6% /boot/efi<br>tmpfs            386M     0  386M   0% /run/user/1000</pre><p>명령어를 통해 용량을 알아보면 /dev/root 다 차있는 걸 확인할 수 있다.</p><p><strong>해결책</strong></p><blockquote>Docker 캐시과 볼륨삭제</blockquote><ul><li>Docker 캐시삭제</li></ul><pre>docekr system prune -a</pre><ul><li>Docker 볼륨 삭제</li></ul><pre>docker volume prune -a</pre><p>캐시와 볼륨을 삭제하면 20% 감소하는 효과를 본 것 같다. 하지만 캐시와 볼륨 삭제를 해준다고 해도 한계는 있다.</p><blockquote>필요없는 파일들 삭제하기</blockquote><p>필요없는 캐시나 로그들을 삭제해 주면 된다. 지우면 20%로는 감소했다. 하지만 이것도 주기적으로 해주지 않으면 다시 볼륨 부족 문제가 뜬다.</p><blockquote>볼륨 업데이트</blockquote><p><a href="https://velog.io/@denver/AWS-EC2-%EC%9A%A9%EB%9F%89-%EB%B6%80%EC%A1%B1-%EB%94%94%EC%8A%A4%ED%81%AC-%ED%99%95%EC%9E%A5">AWS EC2 용량 부족 디스크 확장</a></p><p>이게 제일 방법이다. 위에 있는 2가지 방법을 병행한다고 해도 다시 볼륨 부족 현상이 뜬다. 돈은 좀 더 나가지만 볼륨을 업데이트 해주는 방법이 정신적 육체적으로 편하다. 그리고 디스크 잡아먹는 것들은 도커에서 빼주고 돌리는 게 좋다.(모니터링 툴 등) 볼륨을 업데이트 했다고 해도 자주자주 위에 있는 2개를 해주는 게 좋다.</p><pre>df -h # 디스크 사용량과 파일 시스템 정보를 표시합니다.<br><br>lsblk # 시스템에 연결된 모든 스토리지 블록 장치를 나열합니다.<br><br>sudo growpart /dev/nvme0n1 1 # 디스크의 첫 번째 파티션을 확장합니다.<br><br>sudo resize2fs /dev/nvme0n1p1 # 확장된 파티션의 파일 시스템 크기를 조정합니다.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d90bc2f55b20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comment Notification Feature (Long Polling + NestJS)]]></title>
            <link>https://medium.com/@kawy.sojung/comment-notification-feature-long-polling-nestjs-9299d5da8a11?source=rss-48475f033e55------2</link>
            <guid isPermaLink="false">https://medium.com/p/9299d5da8a11</guid>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[long-polling]]></category>
            <category><![CDATA[comment]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[완두콩]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 14:43:16 GMT</pubDate>
            <atom:updated>2023-11-26T14:44:18.627Z</atom:updated>
            <content:encoded><![CDATA[<h3>Long polling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ui7Wirbgz9rCI74H-bUhVQ.png" /></figure><ul><li>You can maintain a persistent connection with a very simple server without the need for specific protocols like WebSockets or server-sent events.</li><li>The implementation is quite straightforward and can be applied in a variety of scenarios.</li><li>It enables the delivery of messages without any delay.</li></ul><h3>Functionality</h3><ul><li>With Request</li></ul><pre>Client → sends a request → Server (holds the request until new data arrives) → Server sends a response with data → Server connection closes.<br>&lt;Repeat indefinitely&gt;</pre><ul><li>Without Request</li></ul><pre>Client → sends a request → Server (waits until a set timeout) → On timeout, server sends a status update response → Server connection closes.</pre><h3>Nestjs ↔ Long Polling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxnuT3KZoDRw8v5SCIE9ig.png" /></figure><ol><li><strong>Client Initializes Long Polling Request</strong></li></ol><ul><li>The client initializes an HTTP GET request to the server.</li><li>The server waits for a response and remains in a waiting state until the response arrives.</li></ul><p><strong>2. Server Processing the Request</strong></p><ul><li>The server receives the request from the client and delays the response for a set period (continuously checking during this delay).</li><li>When a new comment is posted or the set time passes, the server sends a response to the client.</li></ul><p><strong>3. Client Processing the Response</strong></p><ul><li>Once the client receives a response from the server, it immediately processes the content.</li><li>After the processing is complete, the client sends a request to the server and enters a waiting state.</li></ul><p><strong><em>⇒ </em>This provides real-time comment notifications to the user.</strong></p><h3>Applying to a Project</h3><h4>1. Create a ‘notification’ directory</h4><h4>2. Create dto, controller, and service in the notification directory</h4><h4>3. Create notification.dto</h4><ul><li>Fetch from each of the tables: Board, Node, User</li></ul><pre>import {<br>  Entity,<br>  PrimaryGeneratedColumn,<br>  Column,<br>  ManyToOne,<br>  JoinColumn,<br>} from &#39;typeorm&#39;;<br>import { Board } from &#39;../../board/entities/board.entity&#39;;<br>import { Node } from &#39;../../node/entities/node.entity&#39;;<br>import { ApiProperty } from &#39;@nestjs/swagger&#39;;<br>import { User } from &#39;../../user/entities/user.entity&#39;;<br><br>@Entity(&#39;notification&#39;)<br>export class Notification {<br>  @PrimaryGeneratedColumn(&#39;increment&#39;, { name: &#39;notification_id&#39; })<br>// Defines an auto-incrementing primary key<br>  id: number;<br><br>  @Column()<br>  message: string;<br><br>   @ManyToOne(() =&gt; Node) // Many-to-one relationship with the Node entity<br>  @JoinColumn({ name: &#39;node_id&#39; }) // Uses node_id column as a foreign key. Refers to Node entity<br>  @ApiProperty({ description: &#39;Node associated with the post&#39;, type: () =&gt; Node })<br>  node: Node;<br><br>  @ManyToOne(() =&gt; User) // Many-to-one relationship with the User entity<br>  @JoinColumn({ name: &#39;user_id&#39; }) // Uses user_id column as a foreign key. Refers to User entity<br>  @ApiProperty({ description: &#39;User who wrote the post&#39; })<br>  user: User;<br><br>  @ManyToOne(() =&gt; Board) // Many-to-one relationship with the Board entity<br>  @JoinColumn({ name: &#39;board_id&#39; }) // Uses board_id column as a foreign key. Refers to Board entity<br>  board: Board;<br>}</pre><h4>4. Settings Related to Notifications</h4><blockquote>notification.service.ts</blockquote><ul><li>Configure to update every 30 seconds</li></ul><pre>@Injectable()<br>export class NotificationService {<br>  private readonly TIMEOUT_DURATION = 30000;<br>  // private: &#39;TIMEOUT_DURATION&#39; is accessible only within the class. Prevents direct modification and access from external classes.<br>  // readonly: Once initialized, the value cannot be changed. Once set, the value remains constant and is only used within the class.<br><br>  constructor(<br>    @InjectRepository(Notification)<br>    private notificationRepository: Repository&lt;Notification&gt;,<br>    @InjectRepository(Node)<br>    private nodeRepository: Repository&lt;Node&gt;,<br>    @InjectRepository(User)<br>    private userRepository: Repository&lt;User&gt;,<br>    // Using the @InjectRepository decorator to perform dependency injection for Node, User, Notification repositories<br>    // Efficiently manages data for all three entities. Each repository is used to perform database operations related to its respective entity.<br>  ) {}<br>}</pre><ul><li>@Injectable(): Used to mark a specific class as an &quot;injectable service.&quot; Managed by the dependency injection system, it is automatically injected when needed in other parts of the application.</li><li>TIMEOUT_DURATION: Used to limit the execution time of specific operations. It allows for automatically stopping or failing a request or operation if 30 seconds pass since its start.</li></ul><h4><strong>🌟 Waiting for New Notifications 🌟</strong></h4><blockquote>notification.controller.ts</blockquote><ul><li>Uses Long Polling method.</li><li>A method where the client sends a request to the server, and the server delays the response until a new notification is available, maintaining a ‘waiting’ state.</li></ul><pre>@Get(&#39;longpoll/new&#39;)<br>@ApiOperation({ summary: &#39;Wait for New Notifications&#39; })<br>@ApiResponse({<br>  status: 200,<br>  description: &#39;The new notification has been successfully returned.&#39;,<br>  type: NotificationResponseDTO,<br>})<br>@ApiResponse({ status: 404, description: &#39;User not found.&#39; })<br>@ApiHeader({<br>  name: &#39;user_id&#39;,<br>  required: true,<br>  description: &#39;User ID&#39;,<br>})<br>async waitForNewNotifications(<br>  @Headers(&#39;user_id&#39;) userIdHeader: string,<br>): Promise&lt;NotificationResponseDTO&gt; {<br>  const userId = parseInt(userIdHeader);<br>  if (isNaN(userId)) {<br>    throw new BadRequestException(&#39;userId must be a number&#39;);<br>  }<br>  const notification = await this.notificationService.waitForNewNotifications(<br>    userId,<br>  );<br>  return new NotificationResponseDTO(<br>    notification.message,<br>    notification.board.id,<br>    notification.node.id,<br>    notification.id,<br>  );<br>}</pre><ul><li>Call the waitingForNewNotifications method in the NotificationService. Execute logic that waits until a new notification actually arrives.</li><li>Enable users to receive new comment notifications in real-time through asynchronous processing.</li></ul><blockquote>notification.service.ts</blockquote><pre>public waitingClients: {<br>    userId: number;<br>    resolve: (value: unknown) =&gt; void;<br>    reject: (reason?: any) =&gt; void;<br>    timer: NodeJS.Timeout;<br>  }[] = [];<br><br>  private addToWaitingClients(client: {<br>    userId: number;<br>    resolve: (value: unknown) =&gt; void;<br>    reject: (reason?: any) =&gt; void;<br>    timer: NodeJS.Timeout;<br>  }) {<br>    this.waitingClients.push(client);<br>  }<br><br>  async waitForNewNotifications(userId: number): Promise&lt;Notification&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>      const timer = setTimeout(() =&gt; {<br>        const index = this.waitingClients.findIndex(<br>          (client) =&gt; client.userId === userId,<br>        );<br>        if (index !== -1) {<br>          this.waitingClients.splice(index, 1);<br>          reject(new NoNotificationException());<br>        }<br>      }, this.TIMEOUT_DURATION);<br><br>      this.addToWaitingClients({ userId, resolve, reject, timer });<br>    });<br>  }</pre><ul><li>waitingClients: Manages a list of clients that the server is waiting for new notifications. For each client, this includes the user identifier (userId), a callback to execute upon receiving a notification (resolve), a function to be called in case of timeout or error (reject), and a timer to monitor the waiting period.</li><li>waitingForNewNotifications: Handles two possible scenarios that can occur while a user is waiting for new notifications.</li><li>How waitingForNewNotifications works</li></ul><ol><li>Returns a new Promise, entering a waiting state until a notification arrives or a timeout occurs.</li><li>The setTimeout function executes after the specified TIMEOUT_DURATION (30 seconds), including a callback function to be executed after the given time elapses.</li><li>Within the timer’s callback function, search the this.waitingClients array for a client matching the currently waiting userId.</li><li>If a client with that userId is found in the array, remove the client from the array (adding the current user to the list of waiting clients, resolving when a new notification arrives, and keeping the timer active for the set duration).</li><li>If a client with that userId is not found in the array, remove the user from the waiting list and return a timeout error (removing from the waitingClients array and calling the reject function with a NoNotificationException error).</li><li>this.addToWaitingClients: Adds a new waiting client to the waitingClients array (including userId, resolve, reject functions, and timer). This is used later to notify the client when a new notification arrives.</li></ol><h4>🌟 Retrieving All Notifications for a User 🌟</h4><blockquote>notification.controller.ts</blockquote><pre>@Get()<br>@ApiOperation({ summary: &#39;Retrieve All Notifications for a User&#39; })<br>@ApiResponse({<br>  status: 200,<br>  description: &#39;Notification list has been successfully returned.&#39;,<br>  type: NotificationResponseDTO,<br>  isArray: true,<br>})<br>@ApiHeader({<br>  name: &#39;user_id&#39;,<br>  required: true,<br>  description: &#39;User ID&#39;,<br>})<br>async getNotifications(<br>  @Headers(&#39;user_id&#39;) userIdHeader: string,<br>): Promise&lt;any[]&gt; {<br>  const userId = parseInt(userIdHeader);<br>  if (isNaN(userId)) {<br>    throw new BadRequestException(&#39;userId must be a number&#39;);<br>  }<br><br>  const notifications =<br>    await this.notificationService.getNotificationsForUser(userId);<br><br>  return notifications.map((notification) =&gt; ({<br>    message: notification.message,<br>    board_id: notification.board?.id,<br>    node_id: notification.node?.id,<br>    notification_id: notification.id,<br>  }));<br>}</pre><ul><li>Validates if the user_id value is a valid number. If not, throws a BadRequestException.</li><li>Uses the getNotificationsForUser method from notificationService to retrieve all notifications for the specified userId.</li><li>Used for users to check their notifications and extracts only the necessary information.</li></ul><blockquote>notification.service.ts</blockquote><pre>async getNotificationsForUser(userId: number): Promise&lt;Notification[]&gt; {<br>  return await this.notificationRepository.find({<br>    where: { user: { id: userId } },<br>    relations: [&#39;board&#39;, &#39;node&#39;],<br>    order: { id: &#39;DESC&#39; },<br>  });<br>}</pre><ul><li>Receives a numeric userId parameter and asynchronously returns an array of Notification objects.</li><li>where: Filters to only receive notifications where the user&#39;s id matches the input userId.</li><li>relations: Loads the related board and node entities. Used when board and node information associated with the notification is also required in the result.</li><li>order: Sorts by the id field in descending order to return the most recent notifications first</li></ul><h4>🌟 Deleting Notifications 🌟</h4><blockquote>notification.controller.ts</blockquote><pre>@Delete(&#39;:notificationId&#39;)<br>@ApiOperation({ summary: &#39;Delete Notification&#39; })<br>@ApiResponse({<br>  status: 200,<br>  description: &#39;Notification successfully deleted.&#39;,<br>})<br>@ApiResponse({ status: 404, description: &#39;Notification not found.&#39; })<br>async deleteNotification(<br>  @Param(&#39;notificationId&#39;) notificationId: number,<br>): Promise&lt;{ message: string }&gt; {<br>  await this.notificationService.deleteNotification(notificationId);<br>  return { message: &#39;Notification successfully deleted.&#39; };<br>}</pre><ul><li>Calls the deleteNotification method of notificationService to delete the notification corresponding to the extracted notificationId.</li></ul><blockquote>notification.service.ts</blockquote><pre>async deleteNotification(id: number): Promise&lt;void&gt; {<br>  const result = await this.notificationRepository.delete(id);<br>  if (result.affected === 0) {<br>    throw new NotFoundException(`Notification with ID ${id} not found`);<br>  }<br>}</pre><ul><li>this.notificationRepository.delete(id) to delete the notification with the given id from the database.</li></ul><h4>5. Settings Related to Board ↔ Notification</h4><ul><li>Logic needs to be created to send notifications to the board owner when a comment is made.</li></ul><blockquote>notification.service.ts</blockquote><pre>async createNotificationForBoardOwner(data: {<br>  board: Board;<br>  message: string;<br>  commentId: number;<br>  nodeId: number;<br>  userId: number;<br>}): Promise&lt;Notification&gt; {<br>  // First, fetch the Node and User entities.<br>  const node = await this.nodeRepository.findOneBy({<br>    id: data.nodeId,<br>  } as FindOptionsWhere&lt;Node&gt;);<br>  const user = await this.userRepository.findOneBy({ id: data.userId });<br><br>  // Validate the found Node and User entities.<br>  if (!node) {<br>    throw new NotFoundException(`Node with ID ${data.nodeId} not found`);<br>  }<br>  if (!user) {<br>    throw new NotFoundException(`User with ID ${data.userId} not found`);<br>  }<br><br>  // Create the Notification object.<br>  const newNotification = new Notification();<br>  newNotification.message = data.message;<br>  // Before assigning newNotification.board, the corresponding board object must be fetched, but since there is no logic to fetch it, it cannot be directly used.<br>  newNotification.board = data.board;<br>  newNotification.node = node;<br>  newNotification.user = user;<br><br>  // Save the created Notification object.<br>  const savedNotification = await this.notificationRepository.save(<br>    newNotification,<br>  );<br><br>  // Handle waiting clients.<br>  const waitingClient = this.waitingClients.find(<br>    (client) =&gt; client.userId === data.userId,<br>  );<br>  if (waitingClient) {<br>    console.log(<br>      `[createNotificationForBoardOwner] Found waiting user: ${data.userId}`,<br>    );<br>    clearTimeout(waitingClient.timer);<br>    waitingClient.resolve(savedNotification);<br>    this.waitingClients = this.waitingClients.filter(<br>      (client) =&gt; client.userId !== data.userId,<br>    );<br>  } else {<br>    console.log(<br>      `[createNotificationForBoardOwner] No waiting user found for: ${data.userId}`,<br>    );<br>  }<br><br>  return savedNotification;<br>}</pre><ul><li>Before using newNotification.board = board, you need to add logic to fetch the board object and change board: Board; to boardId: number;.</li><li>Create a new Notification object using the fetched Node and User, and the input board and message.</li><li>Check if the user is currently waiting for a notification in the waitingClients array.</li><li>If there are users waiting, terminate their waiting state, call the resolve function to send the new notification data, and remove the user from the waiting list.</li></ul><h4>6. Settings Related to Comment ↔ Notification</h4><ul><li>Logic needs to be created to send notifications to board users when a comment is made on the board.</li></ul><blockquote>comment.service.ts</blockquote><pre>async createComment(<br>  boardId: number,<br>  userId: string,<br>  createCommentDto: CreateCommentDto,<br>  parentId?: number,<br>): Promise&lt;Comment&gt; {<br>  console.log(<br>    `[createComment] Started comment creation for board ${boardId} by user ${userId}`,<br>  );<br><br>  const user: User = await this.validateUserExists(userId);<br>  const board: Board = await this.validateBoardExists(boardId);<br><br>  const comment: Comment = this.commentMapper.DtoToEntity(<br>    createCommentDto,<br>    user,<br>    board,<br>    user.nickname,<br>  );<br>  const savedComment = await this.commentRepository.save(comment);<br><br>  // Call the createNotificationForBoardOwner method of the notification service to create and send the notification.<br>  await this.notificationService.createNotificationForBoardOwner({<br>    board: board,<br>    message: `${user.nickname} has posted a comment on ${board.title}.`,<br>    commentId: savedComment.id,<br>    nodeId: board.node.id,<br>    userId: board.user.id,<br>  });<br><br>  // Check the userId of the user who created the comment and find any users waiting for notifications based on that userId.<br>  const waitingUser = this.notificationService.waitingClients.find(<br>    (client) =&gt; client.userId === Number(userId),<br>  );<br><br>  if (waitingUser) {<br>    // Send a notification to users who are waiting for it.<br>    await this.notificationService.createNotificationForBoardOwner({<br>      board: board,<br>      message: `A new comment has been posted.`,<br>      commentId: savedComment.id,<br>      nodeId: board.node.id,<br>      userId: Number(userId),<br>    });<br>  }<br><br>  console.log(<br>    `[createComment] Finished comment creation for board ${boardId} by user ${userId}`,<br>  );<br>}</pre><ul><li>notificationService.createNotificationForBoardOwner to create and send a notification to the board owner that a new comment has been posted, passing information like board, user, and the ID of the savedComment.</li><li>Searches the notificationService.waitingClients array to check if the user who posted the comment is waiting.</li><li>If there are waiting users, sends them a notification of the new comment as well.</li></ul><h4>7. Execution Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*X8HQjT_Hr0J-S4IDiHX_FQ.png" /></figure><p><a href="https://tv.kakao.com/v/442096672">https://tv.kakao.com/v/442096672</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9299d5da8a11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[댓글 알림 기능(Long Polling + Nestjs)]]></title>
            <link>https://medium.com/@kawy.sojung/%EB%8C%93%EA%B8%80-%EC%95%8C%EB%A6%BC-%EA%B8%B0%EB%8A%A5-long-polling-nestjs-51adb221341c?source=rss-48475f033e55------2</link>
            <guid isPermaLink="false">https://medium.com/p/51adb221341c</guid>
            <category><![CDATA[long-polling]]></category>
            <category><![CDATA[notification-service]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[notifciaton-contorller]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[완두콩]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 10:01:40 GMT</pubDate>
            <atom:updated>2023-11-26T13:41:43.041Z</atom:updated>
            <content:encoded><![CDATA[<h3>Long polling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ui7Wirbgz9rCI74H-bUhVQ.png" /><figcaption>Long Polling 그림으로 간단하게 설명</figcaption></figure><ul><li><em>웹소켓이나 server-sent event 같은 특정한 프로토콜을 사용하지 않아도 아주 간단한 서버를 지속적인 커넥션을 유지할 수 있음</em></li><li><em>구현이 매우 쉽고 다양한 경우 사용 가능</em></li><li><em>지연없이 메시지를 전달 가능</em></li></ul><h3>기능</h3><ul><li>요청 O</li></ul><pre>클라이언트 → 요청 보냄 → 서버(새 데이터가 도착할 때까지 요청을 보류) → 서버가 데이터를 포함한 응답 보냄 → 서버 연결 닫힘 <br>&lt;무한반복&gt;</pre><ul><li>요청 X</li></ul><pre>클라이언트 → 요청 보냄 → 서버(설정된 타임아웃까지 대기) → 타임아웃 시 서버가 상태 업데이트 응답 보냄 → 서버 연결 닫힘</pre><h3>Nestjs ↔ Long Polling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*zsbjnnBkX0EH0yq-rGMNiA.png" /><figcaption>Long Polling 방식</figcaption></figure><ol><li><strong>Client에서 Long Polling 요청 초기화</strong></li></ol><ul><li>Client은 Server에게 HTTP GET 요청 초기화</li><li>Server는 response(응답)을 기다리며, 응답 오기 전까지는 대기 상태</li></ul><p>2.<strong> Server에서 요청 처리</strong></p><ul><li>Server은 Client로 요청을 받고 설정된 시간 동안 응답을 보류(보류하는 동안 지속적으로 확인)</li><li>새로운 댓글이 달리거나 설정이 지나면, Server → Client 응답 보냄</li></ul><p>3. <strong>Client에서 응답 처리</strong></p><ul><li>Client는 Server에게 응답을 받게 되면, 즉시 내용 처리</li><li>처리가 완료가 된 후, Server에보내 대기 상태에 들어감</li></ul><p><strong><em>⇒ 사용자에게 실시간으로 댓글 알림을 제공</em></strong></p><h3>프로젝트 적용</h3><h4><strong>1. notification 디렉토리 생성</strong></h4><h4>2.<strong> notification에 dto, controller, service 생성</strong></h4><h4>3.<strong> notification.dto 생성</strong></h4><ul><li>Board, Node, User 각각의 테이블에서 가지고 오기</li></ul><pre>import {<br>  Entity,<br>  PrimaryGeneratedColumn,<br>  Column,<br>  ManyToOne,<br>  JoinColumn,<br>} from &#39;typeorm&#39;;<br>import { Board } from &#39;../../board/entities/board.entity&#39;;<br>import { Node } from &#39;../../node/entities/node.entity&#39;;<br>import { ApiProperty } from &#39;@nestjs/swagger&#39;;<br>import { User } from &#39;../../user/entities/user.entity&#39;;<br><br>@Entity(&#39;notification&#39;)<br>export class Notification {<br>  @PrimaryGeneratedColumn(&#39;increment&#39;, { name: &#39;notification_id&#39; })<br>//자동적으로 증가하는 기본 키 정의<br>  id: number;<br><br>  @Column()<br>  message: string;<br><br>  @ManyToOne(() =&gt; Node) //Node 엔티티와 다대일 관계<br>  @JoinColumn({ name: &#39;node_id&#39; }) //node_id 컬럼을 외래키로 사용. Node엔티티 참조<br>  @ApiProperty({ description: &#39;게시글과 연관된 노드&#39;, type: () =&gt; Node })<br>  node: Node;<br><br>  @ManyToOne(() =&gt; User) //User 엔티티와 다대일 관계<br>  @JoinColumn({ name: &#39;user_id&#39; }) //user_id 컬럼을 외래키로 사용. User엔티티 참조<br>  @ApiProperty({ description: &#39;게시글을 작성한 사용자&#39; })<br>  user: User;<br><br>  @ManyToOne(() =&gt; Board) //Board 엔티티 다대일 관계<br>  @JoinColumn({ name: &#39;board_id&#39; }) //board_id 컬럼을 외래키로 사용. Board엔티티 참조<br>  board: Board;<br>}</pre><h4>4. <strong>Notication 관련된 설정</strong></h4><blockquote>notification.service.ts</blockquote><ul><li>30초마다 업데이트 할 수 있게 설정</li></ul><pre>@Injectable()<br>export class NotificationService {<br>  private readonly TIMEOUT_DURATION = 30000;<br>//private: &#39;TIMEOUT_DURATION&#39;이라는 클래스 내부에서만 접근 가능. 외부 클래스 이 변수를 직접적으로 수정 접근 방지<br>//readonly: 변수가 초기화 된 후에는 값을 변경할 수 없음. 한 번 설정되면 그 값이 고정되어 클래스 내에서만 사용<br><br>  constructor(<br>    @InjectRepository(Notification)<br>    private notificationRepository: Repository&lt;Notification&gt;,<br>    @InjectRepository(Node)<br>    private nodeRepository: Repository&lt;Node&gt;,<br>    @InjectRepository(User)<br>    private userRepository: Repository&lt;User&gt;,<br>//@InjectRepository 데코레이터를 사용 Node,User,Notification의 의존성 주입을 통해 가져옴<br>//3개의 데이터를 효율적으로 관리. 각 리포지토리는 해당 엔티티와 관련된 데이터베이스 작업을 수행하는데 사용<br>  ) {}</pre><ul><li>@Injectable() : 특정 클래스를 “주입 가능한 서비스&quot;로 표시하는데 사용. 의존성 주입 시스템에 의해 관리, 애플리케이션의 다른 부분에서 필요할 때 자동으로 주입</li><li>TIMEOUT_DURATION : 특정 작업 실행 시간을 제한하는데 사용. 요청이나 작업이 시작된 후 30초가 지나면 자동으로 중단하거나 실패 처리할 수있도록 함.</li></ul><p>🌟<strong>새로운 알림 대기</strong>🌟</p><blockquote>notification.controller.ts</blockquote><ul><li>Long Polling 방식 사용</li><li>클라이언트가 서버에 요청을 보내고 서버가 새로운 알림이 있을 때까지 응답을 보류하는 방식, 즉 ‘대기’ 상태가 유지 되어야 함</li></ul><pre>@Get(&#39;longpoll/new&#39;)<br>  @ApiOperation({ summary: &#39;새로운 알림 대기&#39; })<br>  @ApiResponse({<br>    status: 200,<br>    description: &#39;새로운 알림이 성공적으로 반환되었습니다.&#39;,<br>    type: NotificationResponseDTO,<br>  })<br>  @ApiResponse({ status: 404, description: &#39;사용자를 찾을 수 없습니다.&#39; })<br>  @ApiHeader({<br>    name: &#39;user_id&#39;,<br>    required: true,<br>    description: &#39;사용자 ID&#39;,<br>  })<br>  async waitForNewNotifications(<br>    @Headers(&#39;user_id&#39;) userIdHeader: string,<br>  ): Promise&lt;NotificationResponseDTO&gt; {<br>    const userId = parseInt(userIdHeader);<br>    if (isNaN(userId)) {<br>      throw new BadRequestException(&#39;userId must be a number&#39;);<br>    }<br>    const notification = await this.notificationService.waitForNewNotifications(<br>      userId,<br>    );<br>    return new NotificationResponseDTO(<br>      notification.message,<br>      notification.board.id,<br>      notification.node.id,<br>      notification.id,<br>    );<br>  }</pre><ul><li>NotificaitonService의 waitingForNewNotificaitons 메소드를 호출. 실제로 새로운 알림이 도착할 때까지 대기하는 로직을 수행</li><li>사용자가 새로운 댓글 알림을 실시간으로 받을 수 있으록 비동기 처리 방식</li></ul><blockquote>notification.service.ts</blockquote><pre>public waitingClients: {<br>    userId: number;<br>    resolve: (value: unknown) =&gt; void;<br>    reject: (reason?: any) =&gt; void;<br>    timer: NodeJS.Timeout;<br>  }[] = [];<br><br>  private addToWaitingClients(client: {<br>    userId: number;<br>    resolve: (value: unknown) =&gt; void;<br>    reject: (reason?: any) =&gt; void;<br>    timer: NodeJS.Timeout;<br>  }) {<br>    this.waitingClients.push(client);<br>  }<br><br>  async waitForNewNotifications(userId: number): Promise&lt;Notification&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>      const timer = setTimeout(() =&gt; {<br>        const index = this.waitingClients.findIndex(<br>          (client) =&gt; client.userId === userId,<br>        );<br>        if (index !== -1) {<br>          this.waitingClients.splice(index, 1);<br>          reject(new NoNotificationException());<br>        }<br>      }, this.TIMEOUT_DURATION);<br><br>      this.addToWaitingClients({ userId, resolve, reject, timer });<br>    });<br>  }</pre><ul><li>waitingClients: 서버가 새로운 알림을 기다리는 있는 클라이언트들의 목록을 관리. 각 클라이언트에 대한 정보로는 사용자 식별자( userId), 알림 수신 시 실행할 콜백(resolve), 타임아웃 또는 오류 시 호출될 함수(reject), 그리고 대기 시간을 감시하는 타이머( timer)가 포함.</li><li>waitingForNewNotificaitons: 사용자가 새 알림을 가디라는 동안 발생할 수 있는 두 상황을 처리</li><li>waitingForNewNotificaitons의 동작 방식</li></ul><ol><li>new Promise를 반환. 알림이 도착하거나 타임아웃이 발생할 때까지 대기 상태가 됨</li><li>setTimeout 함수는 주어진 TIMEOUT_DURATION (30초) 후에 실행. 주어진 시간이 지나면 실행되는 콜백 함수를 가짐</li><li>타이머의 콜백 함수 내에서, this.waitingClients 배열을 검색하여 현재 대기 중인 userId와 일치하는 클라이언트를 찾음</li><li>해당 userId를 가진 클라이언트가 배열 내에 있으면, 해당 클라이언트를 배열에서 제거(호출 현재 사용자를 대기 중인 클라이언트로 추가, resolve 새 알림 도착했을 때 알림 처리, timer 설정된 시간동안 활성화 유지)</li><li>해당 userId를 가진 클라이언트가 배열 내에 없다면, 대기 목록에서 사용자를 제거하고 타임아웃 오류를 반환(waitingClients 배열에서 제거, reject 함수 호출 NoNotificationException 오류 반환)</li><li>this.addToWaitingClients : 새로운 대기 중인 클라이언트를 waitingClients 배열에 추가( userId, resolve, reject 함수와 타이머가 포함). 나중에 새 알림이 도착했을 때 해당 클라이언트를 알릴 때 사용.</li></ol><p>🌟<strong>사용자의 모든 알림 가져오기</strong>🌟</p><blockquote>notification.controller.ts</blockquote><pre>@Get()<br>  @ApiOperation({ summary: &#39;사용자의 모든 알림 가져오기&#39; })<br>  @ApiResponse({<br>    status: 200,<br>    description: &#39;알림 목록이 성공적으로 반환되었습니다.&#39;,<br>    type: NotificationResponseDTO,<br>    isArray: true,<br>  })<br>  @ApiHeader({<br>    name: &#39;user_id&#39;,<br>    required: true,<br>    description: &#39;사용자 ID&#39;,<br>  })<br>  async getNotifications(<br>    @Headers(&#39;user_id&#39;) userIdHeader: string,<br>  ): Promise&lt;any[]&gt; {<br>    const userId = parseInt(userIdHeader);<br>    if (isNaN(userId)) {<br>      throw new BadRequestException(&#39;userId must be a number&#39;);<br>    }<br><br>    const notifications =<br>      await this.notificationService.getNotificationsForUser(userId);<br><br>    return notifications.map((notification) =&gt; ({<br>      message: notification.message,<br>      board_id: notification.board?.id,<br>      node_id: notification.node?.id,<br>      notification_id: notification.id,<br>    }));<br>  }</pre><ul><li>user_id 값이 유효한 숫자인지 확인. 아닐 경우 BadRequestException을 발생</li><li>notificationService의 getNotificationsForUser 메서드를 사용하여 해당 userId의 사용자에 대한 모든 알림을 조회</li><li>자신의 알림을 조회할 때 사용하고 필요한 정보만 추출</li></ul><blockquote>notification.service.ts</blockquote><pre>async getNotificationsForUser(userId: number): Promise&lt;Notification[]&gt; {<br>    return await this.notificationRepository.find({<br>      where: { user: { id: userId } },<br>      relations: [&#39;board&#39;, &#39;node&#39;],<br>      order: { id: &#39;DESC&#39; },<br>    });<br>  }</pre><ul><li>userId숫자 형식의 파라미터를 받고, Notification 객체 배열을 비동기적으로 반환</li><li>where : user의 id가 입력받은 userId와 일치하는 알림만 받게 필터링해줌</li><li>relations :관련된 board와 node 엔티티도 함께 로드. 알림과 연관된 게시판과 노드 정보도 결과에 포함되어야 할 때 사용</li><li>order :id 필드의 내림차순으로 정렬하여, 가장 최근의 알림부터 반환하도록 지정</li></ul><p>🌟<strong>알림 삭제</strong>🌟</p><blockquote>notification.controller.ts</blockquote><pre>@Delete(&#39;:notificationId&#39;)<br>  @ApiOperation({ summary: &#39;알림 삭제&#39; })<br>  @ApiResponse({<br>    status: 200,<br>    description: &#39;성공적으로 알림이 삭제되었습니다.&#39;,<br>  })<br>  @ApiResponse({ status: 404, description: &#39;알림을 찾을 수 없습니다.&#39; })<br>  async deleteNotification(<br>    @Param(&#39;notificationId&#39;) notificationId: number,<br>  ): Promise&lt;{ message: string }&gt; {<br>    await this.notificationService.deleteNotification(notificationId);<br>    return { message: &#39;성공적으로 알림이 삭제되었습니다.&#39; };<br>  }</pre><ul><li>notificationService.deleteNotification 메서드를 호출하여, 추출한 notificationId에 해당하는 알림을 삭제</li></ul><blockquote>notification.service.ts</blockquote><pre>async deleteNotification(id: number): Promise&lt;void&gt; {<br>    const result = await this.notificationRepository.delete(id);<br>    if (result.affected === 0) {<br>      throw new NotFoundException(`Notification with ID ${id} not found`);<br>    }<br>  }</pre><ul><li>this.notificationRepository.delete(id)를 호출하여 주어진 id에 해당하는 알림을 데이터베이스에서 삭제</li></ul><h4>5. <strong>Board↔ Notification 관련된 설정</strong></h4><ul><li>댓글을 달았을 때 게시판 소유자에게 알림을 전송을 해줘야 함.</li><li>게시판 소유자에게 알림을 전송하는 로직</li></ul><blockquote>notification.service.ts</blockquote><pre> async createNotificationForBoardOwner(data: {<br>    board: Board;<br>    message: string;<br>    commentId: number;<br>    nodeId: number;<br>    userId: number;<br>  }): Promise&lt;Notification&gt; {<br>    // 먼저 Node와 User 엔티티를 조회합니다.<br>    const node = await this.nodeRepository.findOneBy({<br>      id: data.nodeId,<br>    } as FindOptionsWhere&lt;Node&gt;);<br>    const user = await this.userRepository.findOneBy({ id: data.userId });<br><br>    // 찾은 Node와 User 엔티티를 검증합니다.<br>    if (!node) {<br>      throw new NotFoundException(`Node with ID ${data.nodeId} not found`);<br>    }<br>    if (!user) {<br>      throw new NotFoundException(`User with ID ${data.userId} not found`);<br>    }<br><br>    // Notification 객체를 생성합니다.<br>    const newNotification = new Notification();<br>    newNotification.message = data.message;<br>//user,node,board 다 다대일인데 board만 다른 이유<br>//newNotificaiton에 할당되기 전에 해당 board객체를 조회해야하지만 조회하는 로직이 없기 때문에 바로 쓸 수 없음<br>    newNotification.board = data.board;<br>    newNotification.node = node;<br>    newNotification.user = user;<br><br>    // 생성된 Notification 객체를 저장합니다.<br>    const savedNotification = await this.notificationRepository.save(<br>      newNotification,<br>    );<br><br>    // 대기 중인 클라이언트를 처리합니다.<br>    const waitingClient = this.waitingClients.find(<br>      (client) =&gt; client.userId === data.userId,<br>    );<br>    if (waitingClient) {<br>      console.log(<br>        `[createNotificationForBoardOwner] Found waiting user: ${data.userId}`,<br>      );<br>      clearTimeout(waitingClient.timer);<br>      waitingClient.resolve(savedNotification);<br>      this.waitingClients = this.waitingClients.filter(<br>        (client) =&gt; client.userId !== data.userId,<br>      );<br>    } else {<br>      console.log(<br>        `[createNotificationForBoardOwner] No waiting user found for: ${data.userId}`,<br>      );<br>    }<br><br>    return savedNotification;<br>  }</pre><ul><li>newNotification.board = board쓰기 위해서는 board 객체 조회하는 로직 추가하고 board:Board; → boardId:number; 변경</li><li>조회된 Node와 User, 그리고 입력된 board와 message를 사용하여 새로운 Notification 객체를 생성</li><li>사용자가 현재 알림을 기다리고 있는지 waitingClients 배열을 확인</li><li>대기 중인 사용자가 있다면, 해당 사용자의 대기 상태를 종료하고 resolve 함수를 호출하여 새 알림 데이터를 전송, 사용자를 대기 목록에서 제거</li></ul><h4>6. Comment↔ Notification 관련된 설정</h4><ul><li>게시판에 댓글을 생성하면서 게시판 사용자에게 알림이 갈 수 있게 로직을 만들어야 줘야 함</li></ul><blockquote>comment.service.ts</blockquote><pre>async createComment(<br>    boardId: number,<br>    userId: string,<br>    createCommentDto: CreateCommentDto,<br>    parentId?: number,<br>  ): Promise&lt;Comment&gt; {<br>    console.log(<br>      `[createComment] Started comment creation for board ${boardId} by user ${userId}`,<br>    );<br><br>    const user: User = await this.validateUserExists(userId);<br>    const board: Board = await this.validateBoardExists(boardId);<br><br>    const comment: Comment = this.commentMapper.DtoToEntity(<br>      createCommentDto,<br>      user,<br>      board,<br>      user.nickname,<br>    );<br>    const savedComment = await this.commentRepository.save(comment);<br><br>    // 알림 서비스의 createNotificationForBoardOwner 메서드를 호출하여 알림 생성 및 전송<br>    await this.notificationService.createNotificationForBoardOwner({<br>      board: board,<br>      message: `${user.nickname}님이 ${board.title}에 댓글을 작성했습니다.`,<br>      commentId: savedComment.id,<br>      nodeId: board.node.id,<br>      userId: board.user.id,<br>    });<br><br>    // 댓글을 생성한 사용자의 userId를 확인하고, 해당 사용자를 기반으로 알림 대기 중인 사용자를 찾습니다.<br>    const waitingUser = this.notificationService.waitingClients.find(<br>      (client) =&gt; client.userId === Number(userId),<br>    );<br><br>    if (waitingUser) {<br>      // 알림을 대기하고 있는 사용자에게 알림을 전송합니다.<br>      await this.notificationService.createNotificationForBoardOwner({<br>        board: board,<br>        message: `새로운 댓글이 작성되었습니다.`,<br>        commentId: savedComment.id,<br>        nodeId: board.node.id,<br>        userId: Number(userId),<br>      });<br>    }<br><br>    console.log(<br>      `[createComment] Finished comment creation for board ${boardId} by user ${userId}`,<br>    );<br>}</pre><ul><li>notificationService.createNotificationForBoardOwner 호출하여 게시판 소유자에게 새 댓글이 작성되었다는 알림을 생성하고 전송. 이때 board, user 정보 및 savedComment의 ID 등을 전달</li><li>notificationService.waitingClients 배열을 검색하여 댓글을 작성한 사용자가 대기 중인지 확인</li><li>대기 중인 사용자가 있으면, 해당 사용자에게도 새로운 댓글 알림을 전송</li></ul><h4>7. 실행결과</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*X8HQjT_Hr0J-S4IDiHX_FQ.png" /></figure><p><a href="https://tv.kakao.com/v/442096672">https://tv.kakao.com/v/442096672</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51adb221341c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>