diff options
Diffstat (limited to 'packages/connect/src')
-rw-r--r-- | packages/connect/src/http_client.ts | 77 | ||||
-rw-r--r-- | packages/connect/src/index.ts | 4 | ||||
-rw-r--r-- | packages/connect/src/schemas/relayer_fees_request_schema.ts | 4 | ||||
-rw-r--r-- | packages/connect/src/schemas/relayer_orderbook_request_schema.ts | 4 | ||||
-rw-r--r-- | packages/connect/src/schemas/relayer_orders_request_schema.ts | 20 | ||||
-rw-r--r-- | packages/connect/src/schemas/relayer_token_pairs_request_schema.ts | 4 | ||||
-rw-r--r-- | packages/connect/src/schemas/schemas.ts | 12 | ||||
-rw-r--r-- | packages/connect/src/types.ts | 25 | ||||
-rw-r--r-- | packages/connect/src/utils/orderbook_channel_message_parser.ts | 37 | ||||
-rw-r--r-- | packages/connect/src/utils/orderbook_channel_message_parsers.ts | 41 | ||||
-rw-r--r-- | packages/connect/src/utils/relayer_response_json_parsers.ts | 37 | ||||
-rw-r--r-- | packages/connect/src/utils/type_converters.ts | 29 | ||||
-rw-r--r-- | packages/connect/src/ws_orderbook_channel.ts | 66 |
13 files changed, 190 insertions, 170 deletions
diff --git a/packages/connect/src/http_client.ts b/packages/connect/src/http_client.ts index 252c9e9dd..3df77b0f0 100644 --- a/packages/connect/src/http_client.ts +++ b/packages/connect/src/http_client.ts @@ -1,11 +1,10 @@ -import {assert} from '@0xproject/assert'; -import {schemas} from '@0xproject/json-schemas'; -import {BigNumber} from 'bignumber.js'; +import { assert } from '@0xproject/assert'; +import { schemas } from '@0xproject/json-schemas'; import 'isomorphic-fetch'; import * as _ from 'lodash'; import * as queryString from 'query-string'; -import {schemas as clientSchemas} from './schemas/schemas'; +import { schemas as clientSchemas } from './schemas/schemas'; import { Client, FeesRequest, @@ -19,19 +18,15 @@ import { TokenPairsItem, TokenPairsRequest, } from './types'; -import {typeConverters} from './utils/type_converters'; - -// TODO: move this and bigNumberConfigs in the 0x.js package into one place -BigNumber.config({ - EXPONENTIAL_AT: 1000, -}); +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 v0 */ export class HttpClient implements Client { - private apiEndpointUrl: string; + private _apiEndpointUrl: string; /** * Instantiates a new HttpClient instance * @param url The relayer API base HTTP url you would like to interact with @@ -39,7 +34,7 @@ export class HttpClient implements Client { */ constructor(url: string) { assert.isHttpUrl('url', url); - this.apiEndpointUrl = url; + this._apiEndpointUrl = url.replace(TRAILING_SLASHES_REGEX, ''); // remove trailing slashes } /** * Retrieve token pair info from the API @@ -54,17 +49,8 @@ export class HttpClient implements Client { const requestOpts = { params: request, }; - const tokenPairs = await this._requestAsync('/token_pairs', HttpRequestType.Get, requestOpts); - assert.doesConformToSchema( - 'tokenPairs', tokenPairs, schemas.relayerApiTokenPairsResponseSchema); - _.each(tokenPairs, (tokenPair: object) => { - typeConverters.convertStringsFieldsToBigNumbers(tokenPair, [ - 'tokenA.minAmount', - 'tokenA.maxAmount', - 'tokenB.minAmount', - 'tokenB.maxAmount', - ]); - }); + const responseJson = await this._requestAsync('/token_pairs', HttpRequestType.Get, requestOpts); + const tokenPairs = relayerResponseJsonParsers.parseTokenPairsJson(responseJson); return tokenPairs; } /** @@ -79,9 +65,8 @@ export class HttpClient implements Client { const requestOpts = { params: request, }; - const orders = await this._requestAsync(`/orders`, HttpRequestType.Get, requestOpts); - assert.doesConformToSchema('orders', orders, schemas.signedOrdersSchema); - _.each(orders, (order: object) => typeConverters.convertOrderStringFieldsToBigNumber(order)); + const responseJson = await this._requestAsync(`/orders`, HttpRequestType.Get, requestOpts); + const orders = relayerResponseJsonParsers.parseOrdersJson(responseJson); return orders; } /** @@ -91,9 +76,8 @@ export class HttpClient implements Client { */ public async getOrderAsync(orderHash: string): Promise<SignedOrder> { assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema); - const order = await this._requestAsync(`/order/${orderHash}`, HttpRequestType.Get); - assert.doesConformToSchema('order', order, schemas.signedOrderSchema); - typeConverters.convertOrderStringFieldsToBigNumber(order); + const responseJson = await this._requestAsync(`/order/${orderHash}`, HttpRequestType.Get); + const order = relayerResponseJsonParsers.parseOrderJson(responseJson); return order; } /** @@ -106,10 +90,9 @@ export class HttpClient implements Client { const requestOpts = { params: request, }; - const orderBook = await this._requestAsync('/orderbook', HttpRequestType.Get, requestOpts); - assert.doesConformToSchema('orderBook', orderBook, schemas.relayerApiOrderBookResponseSchema); - typeConverters.convertOrderbookStringFieldsToBigNumber(orderBook); - return orderBook; + const responseJson = await this._requestAsync('/orderbook', HttpRequestType.Get, requestOpts); + const orderbook = relayerResponseJsonParsers.parseOrderbookResponseJson(responseJson); + return orderbook; } /** * Retrieve fee information from the API @@ -118,18 +101,11 @@ export class HttpClient implements Client { */ public async getFeesAsync(request: FeesRequest): Promise<FeesResponse> { assert.doesConformToSchema('request', request, schemas.relayerApiFeesPayloadSchema); - typeConverters.convertBigNumberFieldsToStrings(request, [ - 'makerTokenAmount', - 'takerTokenAmount', - 'expirationUnixTimestampSec', - 'salt', - ]); const requestOpts = { payload: request, }; - const fees = await this._requestAsync('/fees', HttpRequestType.Post, requestOpts); - assert.doesConformToSchema('fees', fees, schemas.relayerApiFeesResponseSchema); - typeConverters.convertStringsFieldsToBigNumbers(fees, ['makerFee', 'takerFee']); + const responseJson = await this._requestAsync('/fees', HttpRequestType.Post, requestOpts); + const fees = relayerResponseJsonParsers.parseFeesResponseJson(responseJson); return fees; } /** @@ -143,8 +119,11 @@ export class HttpClient implements Client { }; await this._requestAsync('/order', HttpRequestType.Post, requestOpts); } - private async _requestAsync(path: string, requestType: HttpRequestType, - requestOptions?: HttpRequestOptions): Promise<any> { + private async _requestAsync( + path: string, + requestType: HttpRequestType, + requestOptions?: HttpRequestOptions, + ): Promise<any> { const params = _.get(requestOptions, 'params'); const payload = _.get(requestOptions, 'payload'); let query = ''; @@ -152,20 +131,22 @@ export class HttpClient implements Client { const stringifiedParams = queryString.stringify(params); query = `?${stringifiedParams}`; } - const url = `${this.apiEndpointUrl}/v0${path}${query}`; + const url = `${this._apiEndpointUrl}${path}${query}`; const headers = new Headers({ 'content-type': 'application/json', }); - const response = await fetch(url, { method: requestType, body: JSON.stringify(payload), headers, }); + const json = await response.json(); if (!response.ok) { - throw Error(response.statusText); + const errorString = `${response.status} - ${response.statusText}\n${requestType} ${url}\n${JSON.stringify( + json, + )}`; + throw Error(errorString); } - const json = await response.json(); return json; } } diff --git a/packages/connect/src/index.ts b/packages/connect/src/index.ts index ec369a606..a492f5ae9 100644 --- a/packages/connect/src/index.ts +++ b/packages/connect/src/index.ts @@ -1,5 +1,5 @@ -export {HttpClient} from './http_client'; -export {WebSocketOrderbookChannel} from './ws_orderbook_channel'; +export { HttpClient } from './http_client'; +export { WebSocketOrderbookChannel } from './ws_orderbook_channel'; export { Client, ECSignature, diff --git a/packages/connect/src/schemas/relayer_fees_request_schema.ts b/packages/connect/src/schemas/relayer_fees_request_schema.ts index 9408c94a0..f20e077ba 100644 --- a/packages/connect/src/schemas/relayer_fees_request_schema.ts +++ b/packages/connect/src/schemas/relayer_fees_request_schema.ts @@ -2,7 +2,7 @@ export const relayerOrderBookRequestSchema = { id: '/RelayerOrderBookRequest', type: 'object', properties: { - baseTokenAddress: {$ref: '/Address'}, - quoteTokenAddress: {$ref: '/Address'}, + baseTokenAddress: { $ref: '/Address' }, + quoteTokenAddress: { $ref: '/Address' }, }, }; diff --git a/packages/connect/src/schemas/relayer_orderbook_request_schema.ts b/packages/connect/src/schemas/relayer_orderbook_request_schema.ts index 9408c94a0..f20e077ba 100644 --- a/packages/connect/src/schemas/relayer_orderbook_request_schema.ts +++ b/packages/connect/src/schemas/relayer_orderbook_request_schema.ts @@ -2,7 +2,7 @@ export const relayerOrderBookRequestSchema = { id: '/RelayerOrderBookRequest', type: 'object', properties: { - baseTokenAddress: {$ref: '/Address'}, - quoteTokenAddress: {$ref: '/Address'}, + baseTokenAddress: { $ref: '/Address' }, + quoteTokenAddress: { $ref: '/Address' }, }, }; diff --git a/packages/connect/src/schemas/relayer_orders_request_schema.ts b/packages/connect/src/schemas/relayer_orders_request_schema.ts index c11bc77be..570238dae 100644 --- a/packages/connect/src/schemas/relayer_orders_request_schema.ts +++ b/packages/connect/src/schemas/relayer_orders_request_schema.ts @@ -2,15 +2,15 @@ export const relayerOrdersRequestSchema = { id: '/RelayerOrdersRequest', type: 'object', properties: { - exchangeContractAddress: {$ref: '/Address'}, - tokenAddress: {$ref: '/Address'}, - makerTokenAddress: {$ref: '/Address'}, - takerTokenAddress: {$ref: '/Address'}, - tokenA: {$ref: '/Address'}, - tokenB: {$ref: '/Address'}, - maker: {$ref: '/Address'}, - taker: {$ref: '/Address'}, - trader: {$ref: '/Address'}, - feeRecipient: {$ref: '/Address'}, + exchangeContractAddress: { $ref: '/Address' }, + tokenAddress: { $ref: '/Address' }, + makerTokenAddress: { $ref: '/Address' }, + takerTokenAddress: { $ref: '/Address' }, + tokenA: { $ref: '/Address' }, + tokenB: { $ref: '/Address' }, + maker: { $ref: '/Address' }, + taker: { $ref: '/Address' }, + trader: { $ref: '/Address' }, + feeRecipient: { $ref: '/Address' }, }, }; diff --git a/packages/connect/src/schemas/relayer_token_pairs_request_schema.ts b/packages/connect/src/schemas/relayer_token_pairs_request_schema.ts index 8013e1454..379232204 100644 --- a/packages/connect/src/schemas/relayer_token_pairs_request_schema.ts +++ b/packages/connect/src/schemas/relayer_token_pairs_request_schema.ts @@ -2,7 +2,7 @@ export const relayerTokenPairsRequestSchema = { id: '/RelayerTokenPairsRequest', type: 'object', properties: { - tokenA: {$ref: '/Address'}, - tokenB: {$ref: '/Address'}, + tokenA: { $ref: '/Address' }, + tokenB: { $ref: '/Address' }, }, }; diff --git a/packages/connect/src/schemas/schemas.ts b/packages/connect/src/schemas/schemas.ts index 97ac672bf..288d6969d 100644 --- a/packages/connect/src/schemas/schemas.ts +++ b/packages/connect/src/schemas/schemas.ts @@ -1,12 +1,6 @@ -import { - relayerOrderBookRequestSchema, -} from './relayer_orderbook_request_schema'; -import { - relayerOrdersRequestSchema, -} from './relayer_orders_request_schema'; -import { - relayerTokenPairsRequestSchema, -} from './relayer_token_pairs_request_schema'; +import { relayerOrderBookRequestSchema } from './relayer_orderbook_request_schema'; +import { relayerOrdersRequestSchema } from './relayer_orders_request_schema'; +import { relayerTokenPairsRequestSchema } from './relayer_token_pairs_request_schema'; export const schemas = { relayerOrderBookRequestSchema, diff --git a/packages/connect/src/types.ts b/packages/connect/src/types.ts index d02444a3e..edb6c77a6 100644 --- a/packages/connect/src/types.ts +++ b/packages/connect/src/types.ts @@ -1,4 +1,4 @@ -import {BigNumber} from 'bignumber.js'; +import { BigNumber } from '@0xproject/utils'; // TODO: Consolidate Order, SignedOrder and ECSignature into a shared package instead of duplicating them from 0x.js export interface Order { @@ -57,19 +57,24 @@ export interface OrderbookChannelSubscriptionOpts { } export interface OrderbookChannelHandler { - onSnapshot: (channel: OrderbookChannel, subscriptionOpts: OrderbookChannelSubscriptionOpts, - snapshot: OrderbookResponse) => void; - onUpdate: (channel: OrderbookChannel, subscriptionOpts: OrderbookChannelSubscriptionOpts, - order: SignedOrder) => void; - onError: (channel: OrderbookChannel, subscriptionOpts: OrderbookChannelSubscriptionOpts, - err: Error) => void; + onSnapshot: ( + channel: OrderbookChannel, + subscriptionOpts: OrderbookChannelSubscriptionOpts, + snapshot: OrderbookResponse, + ) => void; + onUpdate: ( + channel: OrderbookChannel, + subscriptionOpts: OrderbookChannelSubscriptionOpts, + order: SignedOrder, + ) => void; + onError: (channel: OrderbookChannel, subscriptionOpts: OrderbookChannelSubscriptionOpts, err: Error) => void; onClose: (channel: OrderbookChannel, subscriptionOpts: OrderbookChannelSubscriptionOpts) => void; } export type OrderbookChannelMessage = - SnapshotOrderbookChannelMessage | - UpdateOrderbookChannelMessage | - UnknownOrderbookChannelMessage; + | SnapshotOrderbookChannelMessage + | UpdateOrderbookChannelMessage + | UnknownOrderbookChannelMessage; export enum OrderbookChannelMessageTypes { Snapshot = 'snapshot', diff --git a/packages/connect/src/utils/orderbook_channel_message_parser.ts b/packages/connect/src/utils/orderbook_channel_message_parser.ts new file mode 100644 index 000000000..9a9ca8901 --- /dev/null +++ b/packages/connect/src/utils/orderbook_channel_message_parser.ts @@ -0,0 +1,37 @@ +import { assert } from '@0xproject/assert'; +import { schemas } from '@0xproject/json-schemas'; +import * as _ from 'lodash'; + +import { OrderbookChannelMessage, OrderbookChannelMessageTypes } from '../types'; + +import { relayerResponseJsonParsers } from './relayer_response_json_parsers'; + +export const orderbookChannelMessageParser = { + parse(utf8Data: string): OrderbookChannelMessage { + const messageObj = JSON.parse(utf8Data); + const type: string = _.get(messageObj, 'type'); + assert.assert(!_.isUndefined(type), `Message is missing a type parameter: ${utf8Data}`); + assert.isString('type', type); + switch (type) { + case OrderbookChannelMessageTypes.Snapshot: { + assert.doesConformToSchema('message', messageObj, schemas.relayerApiOrderbookChannelSnapshotSchema); + const orderbookJson = messageObj.payload; + const orderbook = relayerResponseJsonParsers.parseOrderbookResponseJson(orderbookJson); + return _.assign(messageObj, { payload: orderbook }); + } + case OrderbookChannelMessageTypes.Update: { + assert.doesConformToSchema('message', messageObj, schemas.relayerApiOrderbookChannelUpdateSchema); + const orderJson = messageObj.payload; + const order = relayerResponseJsonParsers.parseOrderJson(orderJson); + return _.assign(messageObj, { payload: order }); + } + default: { + return { + type: OrderbookChannelMessageTypes.Unknown, + requestId: 0, + payload: undefined, + }; + } + } + }, +}; diff --git a/packages/connect/src/utils/orderbook_channel_message_parsers.ts b/packages/connect/src/utils/orderbook_channel_message_parsers.ts deleted file mode 100644 index 486a416ef..000000000 --- a/packages/connect/src/utils/orderbook_channel_message_parsers.ts +++ /dev/null @@ -1,41 +0,0 @@ -import {assert} from '@0xproject/assert'; -import {schemas} from '@0xproject/json-schemas'; -import * as _ from 'lodash'; - -import { - OrderbookChannelMessage, - OrderbookChannelMessageTypes, - SignedOrder, -} from '../types'; - -import {typeConverters} from './type_converters'; - -export const orderbookChannelMessageParsers = { - parser(utf8Data: string): OrderbookChannelMessage { - const messageObj = JSON.parse(utf8Data); - const type: string = _.get(messageObj, 'type'); - assert.assert(!_.isUndefined(type), `Message is missing a type parameter: ${utf8Data}`); - assert.isString('type', type); - switch (type) { - case (OrderbookChannelMessageTypes.Snapshot): { - assert.doesConformToSchema('message', messageObj, schemas.relayerApiOrderbookChannelSnapshotSchema); - const orderbook = messageObj.payload; - typeConverters.convertOrderbookStringFieldsToBigNumber(orderbook); - return messageObj; - } - case (OrderbookChannelMessageTypes.Update): { - assert.doesConformToSchema('message', messageObj, schemas.relayerApiOrderbookChannelUpdateSchema); - const order = messageObj.payload; - typeConverters.convertOrderStringFieldsToBigNumber(order); - return messageObj; - } - default: { - return { - type: OrderbookChannelMessageTypes.Unknown, - requestId: 0, - payload: undefined, - }; - } - } - }, -}; diff --git a/packages/connect/src/utils/relayer_response_json_parsers.ts b/packages/connect/src/utils/relayer_response_json_parsers.ts new file mode 100644 index 000000000..668461bf4 --- /dev/null +++ b/packages/connect/src/utils/relayer_response_json_parsers.ts @@ -0,0 +1,37 @@ +import { assert } from '@0xproject/assert'; +import { schemas } from '@0xproject/json-schemas'; +import * as _ from 'lodash'; + +import { FeesResponse, OrderbookResponse, SignedOrder, TokenPairsItem } from '../types'; + +import { typeConverters } from './type_converters'; + +export const relayerResponseJsonParsers = { + parseTokenPairsJson(json: any): TokenPairsItem[] { + assert.doesConformToSchema('tokenPairs', json, schemas.relayerApiTokenPairsResponseSchema); + return json.map((tokenPair: any) => { + return typeConverters.convertStringsFieldsToBigNumbers(tokenPair, [ + 'tokenA.minAmount', + 'tokenA.maxAmount', + 'tokenB.minAmount', + 'tokenB.maxAmount', + ]); + }); + }, + parseOrdersJson(json: any): SignedOrder[] { + assert.doesConformToSchema('orders', json, schemas.signedOrdersSchema); + return json.map((order: object) => typeConverters.convertOrderStringFieldsToBigNumber(order)); + }, + parseOrderJson(json: any): SignedOrder { + assert.doesConformToSchema('order', json, schemas.signedOrderSchema); + return typeConverters.convertOrderStringFieldsToBigNumber(json); + }, + parseOrderbookResponseJson(json: any): OrderbookResponse { + assert.doesConformToSchema('orderBook', json, schemas.relayerApiOrderBookResponseSchema); + return typeConverters.convertOrderbookStringFieldsToBigNumber(json); + }, + parseFeesResponseJson(json: any): FeesResponse { + assert.doesConformToSchema('fees', json, schemas.relayerApiFeesResponseSchema); + return typeConverters.convertStringsFieldsToBigNumbers(json, ['makerFee', 'takerFee']); + }, +}; diff --git a/packages/connect/src/utils/type_converters.ts b/packages/connect/src/utils/type_converters.ts index c136382fd..c1808ce8a 100644 --- a/packages/connect/src/utils/type_converters.ts +++ b/packages/connect/src/utils/type_converters.ts @@ -1,15 +1,17 @@ -import {BigNumber} from 'bignumber.js'; +import { BigNumber } from '@0xproject/utils'; import * as _ from 'lodash'; -// TODO: convert all of these to non-mutating, pure functions export const typeConverters = { - convertOrderbookStringFieldsToBigNumber(orderbook: object): void { - _.each(orderbook, (orders: object[]) => { - _.each(orders, (order: object) => this.convertOrderStringFieldsToBigNumber(order)); - }); + convertOrderbookStringFieldsToBigNumber(orderbook: any): any { + const bids = _.get(orderbook, 'bids', []); + const asks = _.get(orderbook, 'asks', []); + return { + bids: bids.map((order: any) => this.convertOrderStringFieldsToBigNumber(order)), + asks: asks.map((order: any) => this.convertOrderStringFieldsToBigNumber(order)), + }; }, - convertOrderStringFieldsToBigNumber(order: object): void { - this.convertStringsFieldsToBigNumbers(order, [ + convertOrderStringFieldsToBigNumber(order: any): any { + return this.convertStringsFieldsToBigNumbers(order, [ 'makerTokenAmount', 'takerTokenAmount', 'makerFee', @@ -18,14 +20,11 @@ export const typeConverters = { 'salt', ]); }, - convertBigNumberFieldsToStrings(obj: object, fields: string[]): void { - _.each(fields, field => { - _.update(obj, field, (value: BigNumber) => value.toString()); - }); - }, - convertStringsFieldsToBigNumbers(obj: object, fields: string[]): void { + convertStringsFieldsToBigNumbers(obj: any, fields: string[]): any { + const result = _.assign({}, obj); _.each(fields, field => { - _.update(obj, field, (value: string) => new BigNumber(value)); + _.update(result, field, (value: string) => new BigNumber(value)); }); + return result; }, }; diff --git a/packages/connect/src/ws_orderbook_channel.ts b/packages/connect/src/ws_orderbook_channel.ts index 6687025c0..822a022f4 100644 --- a/packages/connect/src/ws_orderbook_channel.ts +++ b/packages/connect/src/ws_orderbook_channel.ts @@ -1,5 +1,5 @@ -import {assert} from '@0xproject/assert'; -import {schemas} from '@0xproject/json-schemas'; +import { assert } from '@0xproject/assert'; +import { schemas } from '@0xproject/json-schemas'; import * as _ from 'lodash'; import * as WebSocket from 'websocket'; @@ -8,21 +8,20 @@ import { OrderbookChannelHandler, OrderbookChannelMessageTypes, OrderbookChannelSubscriptionOpts, - SignedOrder, WebsocketClientEventType, WebsocketConnectionEventType, } from './types'; -import {orderbookChannelMessageParsers} from './utils/orderbook_channel_message_parsers'; +import { orderbookChannelMessageParser } from './utils/orderbook_channel_message_parser'; /** * This class includes all the functionality related to interacting with a websocket endpoint * that implements the standard relayer API v0 */ export class WebSocketOrderbookChannel implements OrderbookChannel { - private apiEndpointUrl: string; - private client: WebSocket.client; - private connectionIfExists?: WebSocket.connection; - private subscriptionCounter = 0; + private _apiEndpointUrl: string; + private _client: WebSocket.client; + private _connectionIfExists?: WebSocket.connection; + private _subscriptionCounter = 0; /** * Instantiates a new WebSocketOrderbookChannel instance * @param url The relayer API base WS url you would like to interact with @@ -30,8 +29,8 @@ export class WebSocketOrderbookChannel implements OrderbookChannel { */ constructor(url: string) { assert.isUri('url', url); - this.apiEndpointUrl = url; - this.client = new WebSocket.client(); + this._apiEndpointUrl = url; + this._client = new WebSocket.client(); } /** * Subscribe to orderbook snapshots and updates from the websocket @@ -42,16 +41,19 @@ export class WebSocketOrderbookChannel implements OrderbookChannel { */ public subscribe(subscriptionOpts: OrderbookChannelSubscriptionOpts, handler: OrderbookChannelHandler): void { assert.doesConformToSchema( - 'subscriptionOpts', subscriptionOpts, schemas.relayerApiOrderbookChannelSubscribePayload); + 'subscriptionOpts', + subscriptionOpts, + schemas.relayerApiOrderbookChannelSubscribePayload, + ); assert.isFunction('handler.onSnapshot', _.get(handler, 'onSnapshot')); assert.isFunction('handler.onUpdate', _.get(handler, 'onUpdate')); assert.isFunction('handler.onError', _.get(handler, 'onError')); assert.isFunction('handler.onClose', _.get(handler, 'onClose')); - this.subscriptionCounter += 1; + this._subscriptionCounter += 1; const subscribeMessage = { type: 'subscribe', channel: 'orderbook', - requestId: this.subscriptionCounter, + requestId: this._subscriptionCounter, payload: subscriptionOpts, }; this._getConnection((error, connection) => { @@ -75,44 +77,50 @@ export class WebSocketOrderbookChannel implements OrderbookChannel { * Close the websocket and stop receiving updates */ public close() { - if (!_.isUndefined(this.connectionIfExists)) { - this.connectionIfExists.close(); + if (!_.isUndefined(this._connectionIfExists)) { + this._connectionIfExists.close(); } } private _getConnection(callback: (error?: Error, connection?: WebSocket.connection) => void) { - if (!_.isUndefined(this.connectionIfExists) && this.connectionIfExists.connected) { - callback(undefined, this.connectionIfExists); + if (!_.isUndefined(this._connectionIfExists) && this._connectionIfExists.connected) { + callback(undefined, this._connectionIfExists); } else { - this.client.on(WebsocketClientEventType.Connect, connection => { - this.connectionIfExists = connection; - callback(undefined, this.connectionIfExists); + this._client.on(WebsocketClientEventType.Connect, connection => { + this._connectionIfExists = connection; + callback(undefined, this._connectionIfExists); }); - this.client.on(WebsocketClientEventType.ConnectFailed, error => { + this._client.on(WebsocketClientEventType.ConnectFailed, error => { callback(error, undefined); }); - this.client.connect(this.apiEndpointUrl); + this._client.connect(this._apiEndpointUrl); } } - private _handleWebSocketMessage(requestId: number, subscriptionOpts: OrderbookChannelSubscriptionOpts, - message: WebSocket.IMessage, handler: OrderbookChannelHandler): void { + private _handleWebSocketMessage( + requestId: number, + subscriptionOpts: OrderbookChannelSubscriptionOpts, + message: WebSocket.IMessage, + handler: OrderbookChannelHandler, + ): void { if (!_.isUndefined(message.utf8Data)) { try { const utf8Data = message.utf8Data; - const parserResult = orderbookChannelMessageParsers.parser(utf8Data); - const type = parserResult.type; + const parserResult = orderbookChannelMessageParser.parse(utf8Data); if (parserResult.requestId === requestId) { switch (parserResult.type) { - case (OrderbookChannelMessageTypes.Snapshot): { + case OrderbookChannelMessageTypes.Snapshot: { handler.onSnapshot(this, subscriptionOpts, parserResult.payload); break; } - case (OrderbookChannelMessageTypes.Update): { + case OrderbookChannelMessageTypes.Update: { handler.onUpdate(this, subscriptionOpts, parserResult.payload); break; } default: { handler.onError( - this, subscriptionOpts, new Error(`Message has missing a type parameter: ${utf8Data}`)); + this, + subscriptionOpts, + new Error(`Message has missing a type parameter: ${utf8Data}`), + ); } } } |