From aa5a867a616464e6405cd02fc88a4b805ae5e55b Mon Sep 17 00:00:00 2001 From: Anton Banchev Date: Thu, 19 Aug 2021 14:00:16 +0200 Subject: [PATCH] just in case ws is slow --- package.json | 3 ++- src/client.js | 12 ++++++++---- src/server/index.js | 2 +- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 2314b3c..d2acd5a 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "express": "^4.17.1", "http-proxy-middleware": "^2.0.1", "lodash": "^4.17.21", - "node-binance-api": "^0.12.5" + "node-binance-api": "^0.12.5", + "node-fetch": "^2.6.1" } } diff --git a/src/client.js b/src/client.js index 8c2763e..a983ba8 100644 --- a/src/client.js +++ b/src/client.js @@ -1,4 +1,5 @@ import Binance from 'node-binance-api'; +import fetch from 'node-fetch'; class Client { client; @@ -46,12 +47,15 @@ class Client { let data = this.klines[symbol + interval]; if (!data) { this.subscribe(symbol, interval); + while (!data || data.length === 0) { + await new Promise(r => setTimeout(r, 100)); + data = this.klines[symbol + interval]; + } } - while (!data || data.length === 0 || !data[data.length - 1] || data[data.length - 1][6] <= Date.now()) { - await new Promise(r => setTimeout(r, 20)); - data = this.klines[symbol + interval]; + if (!data[data.length - 1] || data[data.length - 1][6] <= Date.now()) { + return fetch(`https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=${interval}`).then(resp => resp.json()); } - return data; + return this.klines[symbol + interval]; } } diff --git a/src/server/index.js b/src/server/index.js index f0d9a98..3cc6019 100644 --- a/src/server/index.js +++ b/src/server/index.js @@ -13,7 +13,7 @@ const getServer = async (client) => { app.use(express.json()); router.get('/api/v3/klines', async (req, res) => { - res.send(await client.getCandles(req.query.symbol, req.query.interval)); + client.getCandles(req.query.symbol, req.query.interval).then(result => res.send(result)) }); router.use(createProxyMiddleware({