Reputation: 380
I am trying to update a REST API to API with Websockets and I don't understand how to handle the responses.
With REST API and awaits is easily identify request with response.
But in WebSocket it seems that all the communication is treated in onmessage, mixed and I don't see how to identify it.
How to identify a concrete answer without id in the request?
For example, I connect to a WebSockets API, in this case Kraken (exchange) and once the connection is open, I add an order:
ws.send(JSON.stringify({
'event' : 'addOrder',
'ordertype' : 'limit',
'pair' : 'DAI/USD',
'price' : '0.005',
'token' : this.wsToken,
'type' : 'buy',
'volume' : '6',
}));
And the response obtained in onmessage can be:
{"descr":"buy 6.00000000 DAIUSD @ limit 0.00500","event":"addOrderStatus","status":"ok","txid":"ABABC-ABABC-ABABC"}
The request has no Id, if I launch 10 requests for addOrder and other types I cannot link the request with the response.
What is the logic to work with an API in this way?
Upvotes: 0
Views: 1306
Reputation: 7
useEffect(() => {
new WebSocket('wss://ws.kraken.com').onopen = function () {
this.onclose = () => console.log('SOCKET CLOSED');
this.onmessage = (e) => console.log(JSON.parse(e.data));
this.send(
JSON.stringify({
event: 'subscribe',
pair: ['XBT/USD', 'XBT/EUR', 'ADA/USD'],
subscription: { name: 'ticker' },
}),
(e) => console.log(e),
);
};
}, [isPaused]);
Upvotes: 0