TradingView-API icon indicating copy to clipboard operation
TradingView-API copied to clipboard

TypeError: str.replace is not a function - Handling Buffer Input in parseWSPacket

Open marcin-koziel opened this issue 2 years ago • 3 comments

Describe the bug The bug occurs in the parseWSPacket function, which expects a string input but receives a Buffer object instead. This leads to the TypeError: str.replace is not a function error, as the function tries to perform string operations (i.e., replace) on a Buffer object.

TypeError: str.replace is not a function

To Reproduce I tried reproducing the mentioned bug in a fresh project clone, and it worked as expected. However, the issue persists in another project using the TradingView-API, where a connection is established through the getPrivateIndicators function via WebSocket.

Expected behavior The expected behaviour of the parseWSPacket function is to correctly parse the input data (string) and return an array of TradingView packets. When receiving an input, the function should perform the string operations (i.e., replace and split) without any issues and proceed with parsing the JSON data contained in the input.

marcin-koziel avatar Apr 28 '23 23:04 marcin-koziel

I've submitted a small fix in PR #194 to handle buffer input in the parseWSPacket function by adding a form of validation. This change shouldn't affect the main repo's functionality, as it only extends the function's capability to handle both string and buffer inputs. Even if the bug isn't immediately reproducible for others, this enhancement can only improve the code robustness and shouldn't have any negative impact.

marcin-koziel avatar Apr 29 '23 00:04 marcin-koziel

try str.toString().replace

imnotadriller avatar May 06 '23 17:05 imnotadriller

Try this code

parseWSPacket(str) {
    if (Buffer.isBuffer(str)) {
      return str
        .toString()
        .replace(cleanerRgx, '')
        .split(splitterRgx)
        .map((p) => {
          if (!p) return false
          try {
            return JSON.parse(p)
          } catch (error) {
            console.warn('Cant parse', p)
            return false
          }
        })
        .filter((p) => p)
    }
    return str
      .replace(cleanerRgx, '')
      .split(splitterRgx)
      .map((p) => {
        if (!p) return false
        try {
          return JSON.parse(p)
        } catch (error) {
          console.warn('Cant parse', p)
          return false
        }
      })
      .filter((p) => p)
  },

nguyenthdat avatar May 11 '23 04:05 nguyenthdat