diff options
-rw-r--r-- | lib/api.js | 18 |
1 files changed, 9 insertions, 9 deletions
@@ -33,7 +33,6 @@ async function queue_processor() { const before = new Date(); await send_this(queue.dequeue().element); const duration = new Date() - before; - console.log(before.toISOString(), new Date().toISOString(), duration); if (duration < 400) { // 333 should work, but 400 should still allow some manual requests to go through during development await sleep(400 - duration); } @@ -90,10 +89,11 @@ async function send_this(data) { } fs.writeFileSync('log', JSON.stringify({event: 'send', date: new Date(), data: data}) + '\n', {flag: 'a+'}); let response = await fetch(`https://api.spacetraders.io/v2${data.request.endpoint}`, options); - if (response.ok) { + try { response = await response.json(); switch(response.error?.code) { //case 401: // TODO 401 means a server reset happened + // TODO reject all promises in queue // close database file // rm database file // logrotate @@ -103,17 +103,17 @@ async function send_this(data) { backoffSeconds = response.error.data.retryAfter; queue.enqueue(data, 1); break; - default: // no error! - fs.writeFileSync('log', JSON.stringify({event: 'response', date: new Date(), data: response}) + '\n', {flag: 'a+'}); - return data.resolve(response); - } - } else { - fs.writeFileSync('log', JSON.stringify({event: 'error', date: new Date(), data: response}) + '\n', {flag: 'a+'}); - switch(response.cause?.code) { case 503: // 503 means maintenance mode, let's hold back for 1 minute backoffSeconds = 60; queue.enqueue(data, 1); break; + default: // no error! + fs.writeFileSync('log', JSON.stringify({event: 'response', date: new Date(), data: response}) + '\n', {flag: 'a+'}); + return data.resolve(response); + } + } catch (err) { + fs.writeFileSync('log', JSON.stringify({event: 'error', date: new Date(), data: err}) + '\n', {flag: 'a+'}); + switch(err.cause?.code) { case 'EAI_AGAIN': // DNS lookup timed out error, let's hold back for 5 seconds backoffSeconds = 5; queue.enqueue(data, 1); |