rentorm / 3commas-api-node

NodeJS wrapper for Official 3commas API
GNU General Public License v3.0
43 stars 28 forks source link

Error: invalid json response body, if there is rate limits problem #18

Open Amantel opened 3 years ago

Amantel commented 3 years ago

I get FetchError: invalid json response body at https://api.3commas.io/public/api/ver1/deals?account_id=*** reason: Unexpected token R in JSON at position 0 If I hit it to many times.

Code to replicate:

const run = async function run() {
  const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  const results = await Promise.all(arr.map(async () => client.makeRequest('GET',
    '/public/api/ver1/deals?',
    { account_id: *** })));

  console.log(results);
};

run().catch((err) => { console.log('Caught error', err); });
Amantel commented 3 years ago

As with 3commas API the reponse.text was pretty uniformative I decided to rely on statusText, and here is what final code looks like:

  async makeRequest (method, path, params) {
    if (!this._apiKey || !this._apiSecret) {
      return new Error('missing api key or secret')
    }

    const sig = this.generateSignature(path, querystring.stringify(params))

      let response = await fetch(
        `${this._url}${path}${querystring.stringify(params)}`,
        {
          method: method,
          timeout: 30000,
          agent: '',
          headers: {
            'APIKEY': this._apiKey,
            'Signature': sig
          }
        }
      )
      const contentType = response.headers.get("content-type");
      if (contentType && contentType.indexOf("application/json") !== -1) {
        return await response.json()
      } else {      
        throw response.statusText    
      }    
    }

Basically if there is no response.json I am throwing and relying on user to catch the error.