How do I destructure this Object?

Viewed 45
const WebSocket = require('ws')
let socket = new WebSocket('wss://ftx.com/ws/');


const dataObject = {'op': 'subscribe', 'channel': 'trades', 'market': 'BTC-PERP'};

socket.onopen = function() {

    // Send an initial message
    socket.send(JSON.stringify(dataObject));
    console.log('Connected')

    messages = []

    socket.onmessage = (msg) => {
        const priceData = JSON.parse(msg.data)
        messages.push(priceData.data)
        console.log(priceData.data)

    }



    // Listen for socket closes
    socket.onclose = function(event) {
        console.log('Client notified socket has closed', event);
    };

    // To close the socket....
    // socket.close()

};
[nodemon] starting `node socket-ftx.js`
Connected
undefined
[
  {
    id: 5014962233,
    price: 19280,
    size: 0.03,
    side: 'sell',
    liquidation: false,
    time: '2022-09-22T20:24:52.011309+00:00'
  },
  {
    id: 5014962234,
    price: 19280,
    size: 0.02,
    side: 'sell',
    liquidation: false,
    time: '2022-09-22T20:24:52.011309+00:00'
  },
  {
    id: 5014962235,
    price: 19280,
    size: 0.0047,
    side: 'sell',
    liquidation: false,
    time: '2022-09-22T20:24:52.011309+00:00'
  }
]

I am trying to store the price and size elements into an array, however I can't parse that array from the response.

priceData.data[0].price does not work. It results in a TypeError. I have tested (typeof passed priceData.data) and it logs as an object and not an array. I am confused here...

1 Answers

The problem is likely that the websocket sometimes send you message that are not priceData arrays. You need to add a check before manipulating it as an array.

socket.onopen = function() {

    // Send an initial message
    socket.send(JSON.stringify(dataObject));
    console.log('Connected')

    messages = []

    socket.onmessage = (msg) => {
        // You could start by adding a log on the message, it might help you debug the issue
        // [EDITED OUT as msg is an Event and JSON.stringify will just return an empty object] console.log(`Message value: ${JSON.stringify(msg)}`);
         console.log(`Message value: ${msg.data}`);
        const priceData = JSON.parse(msg.data)
        
        if (Array.isArray(priceData.data) /* you might add an additional check if the msg contains an identifier of the data type */) {
          // Do your array manipulations here
        } else {
          // it's not a priceData array, do something else if needed
        }
    }



    // Listen for socket closes
    socket.onclose = function(event) {
        console.log('Client notified socket has closed', event);
    };

    // To close the socket....
    // socket.close()

};
Related