I'm developing NestJS App which creates a WebSocket to Binance API. I want to get stream output into browser window or postman. But now I can get stream output only in the console. I can't understand how to send these streams in the browser.
Please help
A class that creates WS stream 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 }[]) {
super(coin)
this.baseUrl = 'wss://stream.binance.com:9443/stream?streams='
this.url = coin.map((c) => {
return `${c.symbol.toLowerCase()}usdt@miniTicker`
}).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)
}
})
return stream$
}
}
A service get-data.service.ts
import { Injectable } from '@nestjs/common';
import { map, Observable } from 'rxjs';
import { Coin } from 'src/classes/coin';
import * as coinlist from '../list/coins.json'
@Injectable()
export class GetDataService {
getCoins(): Observable<any[]> {
const coins = new Coin(coinlist)
return coins.getCryptoData().pipe(map((e) => {
console.log(e)
return e
}))
}
}
A controller get-data.controller.ts
import { Controller, Get, Response } from '@nestjs/common';
import { GetDataService } from './get-data.service';
@Controller('getdata')
export class GetDataController {
constructor(private getDataService: GetDataService){}
@Get()
getCoinsData() {
return this.getDataService.getCoins();
}
}