aboutsummaryrefslogtreecommitdiffstats
path: root/packages/connect/src
diff options
context:
space:
mode:
authorHsuan Lee <hsuan@cobinhood.com>2019-01-19 18:42:04 +0800
committerHsuan Lee <hsuan@cobinhood.com>2019-01-19 18:42:04 +0800
commit7ae38906926dc09bc10670c361af0d2bf0050426 (patch)
tree5fb10ae366b987db09e4ddb4bc3ba0f75404ad08 /packages/connect/src
parentb5fd3c72a08aaa6957917d74c333387a16edf66b (diff)
downloaddexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar
dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.gz
dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.bz2
dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.lz
dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.xz
dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.zst
dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.zip
Update dependency packages
Diffstat (limited to 'packages/connect/src')
-rw-r--r--packages/connect/src/globals.d.ts4
-rw-r--r--packages/connect/src/http_client.ts210
-rw-r--r--packages/connect/src/index.ts20
-rw-r--r--packages/connect/src/orders_channel_factory.ts29
-rw-r--r--packages/connect/src/types.ts48
-rw-r--r--packages/connect/src/utils/assert.ts25
-rw-r--r--packages/connect/src/utils/orders_channel_message_parser.ts37
-rw-r--r--packages/connect/src/utils/relayer_response_json_parsers.ts50
-rw-r--r--packages/connect/src/utils/type_converters.ts26
-rw-r--r--packages/connect/src/ws_orders_channel.ts102
10 files changed, 0 insertions, 551 deletions
diff --git a/packages/connect/src/globals.d.ts b/packages/connect/src/globals.d.ts
deleted file mode 100644
index 783b92913..000000000
--- a/packages/connect/src/globals.d.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-declare module '*.json' {
- const value: any;
- export default value;
-}
diff --git a/packages/connect/src/http_client.ts b/packages/connect/src/http_client.ts
deleted file mode 100644
index c52425431..000000000
--- a/packages/connect/src/http_client.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-import { assert } from '@0x/assert';
-import { schemas } from '@0x/json-schemas';
-import {
- APIOrder,
- AssetPairsRequestOpts,
- AssetPairsResponse,
- FeeRecipientsResponse,
- OrderbookRequest,
- OrderbookResponse,
- OrderConfigRequest,
- OrderConfigResponse,
- OrdersRequestOpts,
- OrdersResponse,
- PagedRequestOpts,
- RequestOpts,
- SignedOrder,
-} from '@0x/types';
-import { fetchAsync } from '@0x/utils';
-import * as _ from 'lodash';
-import * as queryString from 'query-string';
-
-import { Client, HttpRequestOptions, HttpRequestType } from './types';
-import { relayerResponseJsonParsers } from './utils/relayer_response_json_parsers';
-
-const TRAILING_SLASHES_REGEX = /\/+$/;
-
-/**
- * This class includes all the functionality related to interacting with a set of HTTP endpoints
- * that implement the standard relayer API v2
- */
-export class HttpClient implements Client {
- private readonly _apiEndpointUrl: string;
- /**
- * Format parameters to be appended to http requests into query string form
- */
- private static _buildQueryStringFromHttpParams(params?: object): string {
- // if params are undefined or empty, return an empty string
- if (_.isUndefined(params) || _.isEmpty(params)) {
- return '';
- }
- // stringify the formatted object
- const stringifiedParams = queryString.stringify(params);
- return `?${stringifiedParams}`;
- }
- /**
- * Instantiates a new HttpClient instance
- * @param url The relayer API base HTTP url you would like to interact with
- * @return An instance of HttpClient
- */
- constructor(url: string) {
- assert.isWebUri('url', url);
- this._apiEndpointUrl = url.replace(TRAILING_SLASHES_REGEX, ''); // remove trailing slashes
- }
- /**
- * Retrieve assetData pair info from the API
- * @param requestOpts Options specifying assetData information to retrieve, page information, and network id.
- * @return The resulting AssetPairsResponse that match the request
- */
- public async getAssetPairsAsync(
- requestOpts?: RequestOpts & AssetPairsRequestOpts & PagedRequestOpts,
- ): Promise<AssetPairsResponse> {
- if (!_.isUndefined(requestOpts)) {
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.assetPairsRequestOptsSchema);
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.pagedRequestOptsSchema);
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.requestOptsSchema);
- }
- const httpRequestOpts = {
- params: requestOpts,
- };
- const responseJson = await this._requestAsync('/asset_pairs', HttpRequestType.Get, httpRequestOpts);
- const assetDataPairs = relayerResponseJsonParsers.parseAssetDataPairsJson(responseJson);
- return assetDataPairs;
- }
- /**
- * Retrieve orders from the API
- * @param requestOpts Options specifying orders to retrieve and page information, page information, and network id.
- * @return The resulting OrdersResponse that match the request
- */
- public async getOrdersAsync(
- requestOpts?: RequestOpts & OrdersRequestOpts & PagedRequestOpts,
- ): Promise<OrdersResponse> {
- if (!_.isUndefined(requestOpts)) {
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.ordersRequestOptsSchema);
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.pagedRequestOptsSchema);
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.requestOptsSchema);
- }
- const httpRequestOpts = {
- params: requestOpts,
- };
- const responseJson = await this._requestAsync(`/orders`, HttpRequestType.Get, httpRequestOpts);
- const orders = relayerResponseJsonParsers.parseOrdersJson(responseJson);
- return orders;
- }
- /**
- * Retrieve a specific order from the API
- * @param orderHash An orderHash generated from the desired order
- * @return The APIOrder that matches the supplied orderHash
- */
- public async getOrderAsync(orderHash: string, requestOpts?: RequestOpts): Promise<APIOrder> {
- if (!_.isUndefined(requestOpts)) {
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.requestOptsSchema);
- }
- assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema);
- const httpRequestOpts = {
- params: requestOpts,
- };
- const responseJson = await this._requestAsync(`/order/${orderHash}`, HttpRequestType.Get, httpRequestOpts);
- const order = relayerResponseJsonParsers.parseAPIOrderJson(responseJson);
- return order;
- }
- /**
- * Retrieve an orderbook from the API
- * @param request An OrderbookRequest instance describing the specific orderbook to retrieve
- * @param requestOpts Options specifying page information, and network id.
- * @return The resulting OrderbookResponse that matches the request
- */
- public async getOrderbookAsync(
- request: OrderbookRequest,
- requestOpts?: RequestOpts & PagedRequestOpts,
- ): Promise<OrderbookResponse> {
- assert.doesConformToSchema('request', request, schemas.orderBookRequestSchema);
- if (!_.isUndefined(requestOpts)) {
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.pagedRequestOptsSchema);
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.requestOptsSchema);
- }
- const httpRequestOpts = {
- params: _.defaults({}, request, requestOpts),
- };
- const responseJson = await this._requestAsync('/orderbook', HttpRequestType.Get, httpRequestOpts);
- const orderbook = relayerResponseJsonParsers.parseOrderbookResponseJson(responseJson);
- return orderbook;
- }
- /**
- * Retrieve fee information from the API
- * @param request A OrderConfigRequest instance describing the specific fees to retrieve
- * @param requestOpts Options specifying network id.
- * @return The resulting OrderConfigResponse that matches the request
- */
- public async getOrderConfigAsync(
- request: OrderConfigRequest,
- requestOpts?: RequestOpts,
- ): Promise<OrderConfigResponse> {
- if (!_.isUndefined(requestOpts)) {
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.requestOptsSchema);
- }
- assert.doesConformToSchema('request', request, schemas.orderConfigRequestSchema);
- const httpRequestOpts = {
- params: requestOpts,
- payload: request,
- };
- const responseJson = await this._requestAsync('/order_config', HttpRequestType.Post, httpRequestOpts);
- const fees = relayerResponseJsonParsers.parseOrderConfigResponseJson(responseJson);
- return fees;
- }
- /**
- * Retrieve the list of fee recipient addresses used by the relayer.
- * @param requestOpts Options specifying page information, and network id.
- * @return The resulting FeeRecipientsResponse
- */
- public async getFeeRecipientsAsync(requestOpts?: RequestOpts & PagedRequestOpts): Promise<FeeRecipientsResponse> {
- if (!_.isUndefined(requestOpts)) {
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.pagedRequestOptsSchema);
- assert.doesConformToSchema('requestOpts', requestOpts, schemas.requestOptsSchema);
- }
- const httpRequestOpts = {
- params: requestOpts,
- };
- const feeRecipients = await this._requestAsync('/fee_recipients', HttpRequestType.Get, httpRequestOpts);
- assert.doesConformToSchema('feeRecipients', feeRecipients, schemas.relayerApiFeeRecipientsResponseSchema);
- return feeRecipients;
- }
- /**
- * Submit a signed order to the API
- * @param signedOrder A SignedOrder instance to submit
- * @param requestOpts Options specifying network id.
- */
- public async submitOrderAsync(signedOrder: SignedOrder, requestOpts?: RequestOpts): Promise<void> {
- assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
- const httpRequestOpts = {
- params: requestOpts,
- payload: signedOrder,
- };
- await this._requestAsync('/order', HttpRequestType.Post, httpRequestOpts);
- }
- private async _requestAsync(
- path: string,
- requestType: HttpRequestType,
- requestOptions?: HttpRequestOptions,
- ): Promise<any> {
- const params = _.get(requestOptions, 'params');
- const payload = _.get(requestOptions, 'payload');
- const query = HttpClient._buildQueryStringFromHttpParams(params);
- const url = `${this._apiEndpointUrl}${path}${query}`;
- const headers = new Headers({
- 'content-type': 'application/json',
- });
- const response = await fetchAsync(url, {
- method: requestType,
- body: JSON.stringify(payload),
- headers,
- });
- const text = await response.text();
- if (!response.ok) {
- const errorString = `${response.status} - ${response.statusText}\n${requestType} ${url}\n${text}`;
- throw Error(errorString);
- }
- const result = !_.isEmpty(text) ? JSON.parse(text) : undefined;
- return result;
- }
-}
diff --git a/packages/connect/src/index.ts b/packages/connect/src/index.ts
deleted file mode 100644
index f319d63cb..000000000
--- a/packages/connect/src/index.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-export { HttpClient } from './http_client';
-export { ordersChannelFactory } from './orders_channel_factory';
-export { Client, OrdersChannel, OrdersChannelHandler } from './types';
-export {
- APIOrder,
- AssetPairsRequestOpts,
- AssetPairsResponse,
- FeeRecipientsResponse,
- OrderbookRequest,
- OrderbookResponse,
- OrderConfigRequest,
- OrderConfigResponse,
- OrdersChannelSubscriptionOpts,
- OrdersRequestOpts,
- OrdersResponse,
- PagedRequestOpts,
- PaginatedCollection,
- RequestOpts,
- SignedOrder,
-} from '@0x/types';
diff --git a/packages/connect/src/orders_channel_factory.ts b/packages/connect/src/orders_channel_factory.ts
deleted file mode 100644
index 5986d2a77..000000000
--- a/packages/connect/src/orders_channel_factory.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import * as WebSocket from 'websocket';
-
-import { OrdersChannel, OrdersChannelHandler } from './types';
-import { assert } from './utils/assert';
-import { WebSocketOrdersChannel } from './ws_orders_channel';
-
-export const ordersChannelFactory = {
- /**
- * Instantiates a new WebSocketOrdersChannel instance
- * @param url The relayer API base WS url you would like to interact with
- * @param handler An OrdersChannelHandler instance that responds to various
- * channel updates
- * @return An OrdersChannel Promise
- */
- async createWebSocketOrdersChannelAsync(url: string, handler: OrdersChannelHandler): Promise<OrdersChannel> {
- assert.isUri('url', url);
- assert.isOrdersChannelHandler('handler', handler);
- return new Promise<OrdersChannel>((resolve, reject) => {
- const client = new WebSocket.w3cwebsocket(url);
- client.onopen = () => {
- const ordersChannel = new WebSocketOrdersChannel(client, handler);
- resolve(ordersChannel);
- };
- client.onerror = err => {
- reject(err);
- };
- });
- },
-};
diff --git a/packages/connect/src/types.ts b/packages/connect/src/types.ts
deleted file mode 100644
index 08a4506ac..000000000
--- a/packages/connect/src/types.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import {
- APIOrder,
- AssetPairsItem,
- AssetPairsRequestOpts,
- FeeRecipientsResponse,
- OrderbookRequest,
- OrderbookResponse,
- OrderConfigRequest,
- OrderConfigResponse,
- OrdersChannelSubscriptionOpts,
- OrdersRequestOpts,
- PagedRequestOpts,
- PaginatedCollection,
- SignedOrder,
-} from '@0x/types';
-
-export interface Client {
- getAssetPairsAsync: (
- requestOpts?: AssetPairsRequestOpts & PagedRequestOpts,
- ) => Promise<PaginatedCollection<AssetPairsItem>>;
- getOrdersAsync: (requestOpts?: OrdersRequestOpts & PagedRequestOpts) => Promise<PaginatedCollection<APIOrder>>;
- getOrderAsync: (orderHash: string) => Promise<APIOrder>;
- getOrderbookAsync: (request: OrderbookRequest, requestOpts?: PagedRequestOpts) => Promise<OrderbookResponse>;
- getOrderConfigAsync: (request: OrderConfigRequest) => Promise<OrderConfigResponse>;
- getFeeRecipientsAsync: (requestOpts?: PagedRequestOpts) => Promise<FeeRecipientsResponse>;
- submitOrderAsync: (signedOrder: SignedOrder) => Promise<void>;
-}
-
-export interface OrdersChannel {
- subscribe: (subscriptionOpts: OrdersChannelSubscriptionOpts) => void;
- close: () => void;
-}
-
-export interface OrdersChannelHandler {
- onUpdate: (channel: OrdersChannel, subscriptionOpts: OrdersChannelSubscriptionOpts, orders: APIOrder[]) => void;
- onError: (channel: OrdersChannel, err: Error, subscriptionOpts?: OrdersChannelSubscriptionOpts) => void;
- onClose: (channel: OrdersChannel) => void;
-}
-
-export interface HttpRequestOptions {
- params?: object;
- payload?: object;
-}
-
-export enum HttpRequestType {
- Get = 'GET',
- Post = 'POST',
-}
diff --git a/packages/connect/src/utils/assert.ts b/packages/connect/src/utils/assert.ts
deleted file mode 100644
index de7536ffe..000000000
--- a/packages/connect/src/utils/assert.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { assert as sharedAssert } from '@0x/assert';
-// HACK: We need those two unused imports because they're actually used by sharedAssert which gets injected here
-// tslint:disable-next-line:no-unused-variable
-import { Schema, schemas } from '@0x/json-schemas';
-// tslint:disable-next-line:no-unused-variable
-import { ECSignature } from '@0x/types';
-// tslint:disable-next-line:no-unused-variable
-import { BigNumber } from '@0x/utils';
-import * as _ from 'lodash';
-
-export const assert = {
- ...sharedAssert,
- isOrdersChannelSubscriptionOpts(variableName: string, subscriptionOpts: any): void {
- sharedAssert.doesConformToSchema(
- variableName,
- subscriptionOpts,
- schemas.relayerApiOrdersChannelSubscribePayloadSchema,
- );
- },
- isOrdersChannelHandler(variableName: string, handler: any): void {
- sharedAssert.isFunction(`${variableName}.onUpdate`, _.get(handler, 'onUpdate'));
- sharedAssert.isFunction(`${variableName}.onError`, _.get(handler, 'onError'));
- sharedAssert.isFunction(`${variableName}.onClose`, _.get(handler, 'onClose'));
- },
-};
diff --git a/packages/connect/src/utils/orders_channel_message_parser.ts b/packages/connect/src/utils/orders_channel_message_parser.ts
deleted file mode 100644
index 1306a74b1..000000000
--- a/packages/connect/src/utils/orders_channel_message_parser.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { assert } from '@0x/assert';
-import { schemas } from '@0x/json-schemas';
-import * as _ from 'lodash';
-
-import { OrdersChannelMessage, OrdersChannelMessageTypes } from '@0x/types';
-
-import { relayerResponseJsonParsers } from './relayer_response_json_parsers';
-
-export const ordersChannelMessageParser = {
- parse(utf8Data: string): OrdersChannelMessage {
- // parse the message
- const messageObj = JSON.parse(utf8Data);
- // ensure we have a type parameter to switch on
- const type: string = _.get(messageObj, 'type');
- assert.assert(!_.isUndefined(type), `Message is missing a type parameter: ${utf8Data}`);
- assert.isString('type', type);
- // ensure we have a request id for the resulting message
- const requestId: string = _.get(messageObj, 'requestId');
- assert.assert(!_.isUndefined(requestId), `Message is missing a requestId parameter: ${utf8Data}`);
- assert.isString('requestId', requestId);
- switch (type) {
- case OrdersChannelMessageTypes.Update: {
- assert.doesConformToSchema('message', messageObj, schemas.relayerApiOrdersChannelUpdateSchema);
- const ordersJson = messageObj.payload;
- const orders = relayerResponseJsonParsers.parseAPIOrdersJson(ordersJson);
- return _.assign(messageObj, { payload: orders });
- }
- default: {
- return {
- type: OrdersChannelMessageTypes.Unknown,
- requestId,
- payload: undefined,
- };
- }
- }
- },
-};
diff --git a/packages/connect/src/utils/relayer_response_json_parsers.ts b/packages/connect/src/utils/relayer_response_json_parsers.ts
deleted file mode 100644
index 2b1a658d1..000000000
--- a/packages/connect/src/utils/relayer_response_json_parsers.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { assert } from '@0x/assert';
-import { schemas } from '@0x/json-schemas';
-import { orderParsingUtils } from '@0x/order-utils';
-
-import {
- APIOrder,
- AssetPairsItem,
- AssetPairsResponse,
- OrderbookResponse,
- OrderConfigResponse,
- OrdersResponse,
-} from '@0x/types';
-
-import { typeConverters } from './type_converters';
-
-export const relayerResponseJsonParsers = {
- parseAssetDataPairsJson(json: any): AssetPairsResponse {
- assert.doesConformToSchema('assetDataPairsResponse', json, schemas.relayerApiAssetDataPairsResponseSchema);
- return { ...json, records: relayerResponseJsonParsers.parseAssetPairsItemsJson(json.records) };
- },
- parseAssetPairsItemsJson(json: any): AssetPairsItem[] {
- return json.map((assetDataPair: any) => {
- return orderParsingUtils.convertStringsFieldsToBigNumbers(assetDataPair, [
- 'assetDataA.minAmount',
- 'assetDataA.maxAmount',
- 'assetDataB.minAmount',
- 'assetDataB.maxAmount',
- ]);
- });
- },
- parseOrdersJson(json: any): OrdersResponse {
- assert.doesConformToSchema('relayerApiOrdersResponse', json, schemas.relayerApiOrdersResponseSchema);
- return { ...json, records: relayerResponseJsonParsers.parseAPIOrdersJson(json.records) };
- },
- parseAPIOrdersJson(json: any): APIOrder[] {
- return json.map(relayerResponseJsonParsers.parseAPIOrderJson.bind(relayerResponseJsonParsers));
- },
- parseAPIOrderJson(json: any): APIOrder {
- assert.doesConformToSchema('relayerApiOrder', json, schemas.relayerApiOrderSchema);
- return typeConverters.convertAPIOrderStringFieldsToBigNumber(json);
- },
- parseOrderbookResponseJson(json: any): OrderbookResponse {
- assert.doesConformToSchema('orderBookResponse', json, schemas.relayerApiOrderbookResponseSchema);
- return typeConverters.convertOrderbookStringFieldsToBigNumber(json);
- },
- parseOrderConfigResponseJson(json: any): OrderConfigResponse {
- assert.doesConformToSchema('orderConfigResponse', json, schemas.relayerApiOrderConfigResponseSchema);
- return orderParsingUtils.convertStringsFieldsToBigNumbers(json, ['makerFee', 'takerFee']);
- },
-};
diff --git a/packages/connect/src/utils/type_converters.ts b/packages/connect/src/utils/type_converters.ts
deleted file mode 100644
index b262a516b..000000000
--- a/packages/connect/src/utils/type_converters.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { orderParsingUtils } from '@0x/order-utils';
-import * as _ from 'lodash';
-
-import { APIOrder } from '@0x/types';
-
-export const typeConverters = {
- convertOrderbookStringFieldsToBigNumber(orderbook: any): any {
- const bids = _.get(orderbook, 'bids', []);
- const asks = _.get(orderbook, 'asks', []);
- const convertedBids = {
- ...bids,
- records: bids.records.map((order: any) => typeConverters.convertAPIOrderStringFieldsToBigNumber(order)),
- };
- const convertedAsks = {
- ...asks,
- records: asks.records.map((order: any) => typeConverters.convertAPIOrderStringFieldsToBigNumber(order)),
- };
- return {
- bids: convertedBids,
- asks: convertedAsks,
- };
- },
- convertAPIOrderStringFieldsToBigNumber(apiOrder: any): APIOrder {
- return { ...apiOrder, order: orderParsingUtils.convertOrderStringFieldsToBigNumber(apiOrder.order) };
- },
-};
diff --git a/packages/connect/src/ws_orders_channel.ts b/packages/connect/src/ws_orders_channel.ts
deleted file mode 100644
index 70a357c61..000000000
--- a/packages/connect/src/ws_orders_channel.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { OrdersChannelMessageTypes, OrdersChannelSubscriptionOpts } from '@0x/types';
-import * as _ from 'lodash';
-import { v4 as uuid } from 'uuid';
-import * as WebSocket from 'websocket';
-
-import { OrdersChannel, OrdersChannelHandler } from './types';
-import { assert } from './utils/assert';
-import { ordersChannelMessageParser } from './utils/orders_channel_message_parser';
-
-export interface OrdersChannelSubscriptionOptsMap {
- [key: string]: OrdersChannelSubscriptionOpts;
-}
-
-/**
- * This class includes all the functionality related to interacting with a websocket endpoint
- * that implements the standard relayer API v0
- */
-export class WebSocketOrdersChannel implements OrdersChannel {
- private readonly _client: WebSocket.w3cwebsocket;
- private readonly _handler: OrdersChannelHandler;
- private readonly _subscriptionOptsMap: OrdersChannelSubscriptionOptsMap = {};
- /**
- * Instantiates a new WebSocketOrdersChannel instance
- * @param client A WebSocket client
- * @param handler An OrdersChannelHandler instance that responds to various
- * channel updates
- * @return An instance of WebSocketOrdersChannel
- */
- constructor(client: WebSocket.w3cwebsocket, handler: OrdersChannelHandler) {
- assert.isOrdersChannelHandler('handler', handler);
- // set private members
- this._client = client;
- this._handler = handler;
- // attach client callbacks
- this._client.onerror = err => {
- this._handler.onError(this, err);
- };
- this._client.onclose = () => {
- this._handler.onClose(this);
- };
- this._client.onmessage = message => {
- this._handleWebSocketMessage(message);
- };
- }
- /**
- * Subscribe to orderbook snapshots and updates from the websocket
- * @param subscriptionOpts An OrdersChannelSubscriptionOpts instance describing which
- * assetData pair to subscribe to
- */
- public subscribe(subscriptionOpts: OrdersChannelSubscriptionOpts): void {
- assert.isOrdersChannelSubscriptionOpts('subscriptionOpts', subscriptionOpts);
- assert.assert(this._client.readyState === WebSocket.w3cwebsocket.OPEN, 'WebSocket connection is closed');
- const requestId = uuid();
- this._subscriptionOptsMap[requestId] = subscriptionOpts;
- const subscribeMessage = {
- type: 'subscribe',
- channel: 'orders',
- requestId,
- payload: subscriptionOpts,
- };
- this._client.send(JSON.stringify(subscribeMessage));
- }
- /**
- * Close the websocket and stop receiving updates
- */
- public close(): void {
- this._client.close();
- }
- private _handleWebSocketMessage(message: any): void {
- if (_.isUndefined(message.data)) {
- this._handler.onError(this, new Error(`Message does not contain data. Url: ${this._client.url}`));
- return;
- }
- try {
- const data = message.data;
- const parserResult = ordersChannelMessageParser.parse(data);
- const subscriptionOpts = this._subscriptionOptsMap[parserResult.requestId];
- if (_.isUndefined(subscriptionOpts)) {
- this._handler.onError(
- this,
- new Error(`Message has unknown requestId. Url: ${this._client.url} Message: ${data}`),
- );
- return;
- }
- switch (parserResult.type) {
- case OrdersChannelMessageTypes.Update: {
- this._handler.onUpdate(this, subscriptionOpts, parserResult.payload);
- break;
- }
- default: {
- this._handler.onError(
- this,
- new Error(`Message has unknown type parameter. Url: ${this._client.url} Message: ${data}`),
- subscriptionOpts,
- );
- }
- }
- } catch (error) {
- this._handler.onError(this, error);
- }
- }
-}