From 1853bd1268b654ab8e9b1a7c096398b47d58b9a7 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Mon, 5 Jun 2023 23:53:08 +0200 Subject: Hold back on maintenance or rate limiting events --- lib/api.js | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) (limited to 'lib') diff --git a/lib/api.js b/lib/api.js index 4ee5c5d..8ece296 100644 --- a/lib/api.js +++ b/lib/api.js @@ -63,20 +63,31 @@ function send_this(data) { fs.writeFileSync('log', JSON.stringify({event: 'send', date: new Date(), data: data}) + '\n', {flag: 'a+'}); fetch(`https://api.spacetraders.io/v2${data.request.endpoint}`, options) .then(response => response.json()) - .then(response => { - fs.writeFileSync('log', JSON.stringify({event: 'response', date: new Date(), data: response}) + '\n', {flag: 'a+'}); - return data.resolve(response);}) - .catch(err => { + .then(async response => { + switch(response.error?.code) { + case 429: // 429 means rate limited, let's hold back for 10 seconds + await sleep(10000); + queue.enqueue(data, 1); + break; + default: + fs.writeFileSync('log', JSON.stringify({event: 'response', date: new Date(), data: response}) + '\n', {flag: 'a+'}); + return data.resolve(response); + }}) + .catch(async err => { fs.writeFileSync('log', JSON.stringify({event: 'error', date: new Date(), data: err}) + '\n', {flag: 'a+'}); switch(err.cause?.code) { + case 503: // 503 means maintenance mode, let's hold back for 1 minute + await sleep(60000); + queue.enqueue(data, 1); + break; case 'ECONNRESET': - send_this(data); + queue.enqueue(data, 1); break; case 'UND_ERR_CONNECT_TIMEOUT': - send_this(data); + queue.enqueue(data, 1); break; default: - data.reject(err) + data.reject(err); }}); setTimeout(send_next, 400); // 333 should work, but 400 will still allow manual requests to go through during development } -- cgit v1.2.3