Why I got only first item | NestJS, WebSocket, Socket.io


I’m developing NestJS app which asks Binance Websocket API for some data. And also created a WebSocket server that sends received data to Front. On the Back side I got all data in console.log. But on the Front I got only the first item. I can’t understand what’s wrong. Can you help me please?

Coin.gateway.ts

import { MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Server } from 'socket.io';
import { from, of, take, map, Observable } from 'rxjs';
import { Coin } from './classes/coin';
import * as coinlist from './list/coins.json'


@WebSocketGateway(811, {transports: ['websocket', 'polling'], cors: true})
export class CoinGateway {

  @WebSocketServer()
  server: Server;

  @SubscribeMessage('events')
  handleMessage(@MessageBody() data: any) {
    console.log('data',data)
    const coins = new Coin(coinlist, 'usdt', 'miniTicker')
    return coins.getCryptoData().pipe(map((c) => {
      return c
    }))
  }
}

Coin.ts

import { GetCryptocurrencies } from "./abstract/get-cryptocurrencies";
import { WebSocket } from "ws";
import { Logger } from "@nestjs/common";
import { Observable } from "rxjs";

export class Coin extends GetCryptocurrencies {
    private readonly logger = new Logger(Coin.name)
    private baseUrl: string
    private url: string
    constructor(coin: { name: string, symbol: string }[], pair: string, method: string) {
        super(coin, pair, method)
        this.baseUrl = 'wss://stream.binance.com:9443/stream?streams='
        this.url = coin.map((c) => {
            return `${c.symbol.toLowerCase()}${pair}@${method}`
        }).join('/')
        }

    getCryptoData(): any {
        const stream$ = new Observable((observer) => {

            const ws = new WebSocket(`${this.baseUrl}${this.url}`)
            ws.on('open', () => {
                this.logger.log('Connection established')
            })
            ws.onmessage = (msg: any) => {
                const message = JSON.parse(msg.data)
                observer.next(message)
            }
            ws.on('close', () => {
                this.logger.log('Connection closed')
            })
        })
        return stream$
    }
}

Client UI useEffect hook

useEffect(() => {
    const socket = io('ws://localhost:811', {transports: ['websocket']})
    socket.on('connect', () => {
        console.log('Connection established from client')

        socket.emit('events', '', (res: any) => {
            console.log(res)
        })
        const engine = socket.io.engine;
        console.log(engine.transport.name); // in most cases, prints "polling"

        engine.once("upgrade", () => {
            // called when the transport is upgraded (i.e. from HTTP long-polling to WebSocket)
            console.log(engine.transport.name); // in most cases, prints "websocket"
        });

        engine.on("packetCreate", ({ type, data }) => {
            // called for each packet sent
            console.log('Stype', type)
            console.log('Sdata', data)
        });

    })
    }, [])

Source: JavaSript – Stack Overflow

November 20, 2021
Category : News
Tags: javascript | nestjs | socket.io | websocket

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.