aboutsummaryrefslogtreecommitdiffstats
path: root/packages/connect/src/orderbook_channel_factory.ts
blob: 5134af323052e6daa03e2f3fffcaa51bd669bf73 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import * as WebSocket from 'websocket';

import { OrderbookChannel, OrderbookChannelHandler } from './types';
import { assert } from './utils/assert';
import { WebSocketOrderbookChannel } from './ws_orderbook_channel';

export const orderbookChannelFactory = {
    /**
     * Instantiates a new WebSocketOrderbookChannel instance
     * @param   url                  The relayer API base WS url you would like to interact with
     * @param   handler              An OrderbookChannelHandler instance that responds to various
     *                               channel updates
     * @return  An OrderbookChannel Promise
     */
    async createWebSocketOrderbookChannelAsync(
        url: string,
        handler: OrderbookChannelHandler,
    ): Promise<OrderbookChannel> {
        assert.isUri('url', url);
        assert.isOrderbookChannelHandler('handler', handler);
        return new Promise<OrderbookChannel>((resolve, reject) => {
            const client = new WebSocket.w3cwebsocket(url);
            client.onopen = () => {
                const orderbookChannel = new WebSocketOrderbookChannel(client, handler);
                resolve(orderbookChannel);
            };
            client.onerror = err => {
                reject(err);
            };
        });
    },
};