Skip to content
This repository was archived by the owner on Feb 22, 2024. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 1 addition & 14 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,31 +1,18 @@
{
"parser": "babel-eslint",
"extends": "eslint-config-airbnb",
"extends": "binary",
"env": {
"browser": true,
"es6": true,
"jest": true
},
"rules": {
"indent": [0, 4],
"camelcase": 0,
"no-tabs": 0,
"no-undef": 0,
"comma-dangle": 0,
"no-plusplus": 0,
"arrow-parens": 0,
"no-mixed-operators": 0,
"object-property-newline": 0,
"max-len": [1, 150, 4],
"prefer-template": 0,
"no-confusing-arrow": 0,
"no-param-reassign": 0,
"react/jsx-indent": [0, "tab"],
"react/prefer-stateless-function": 0,
"react/jsx-indent-props": [0, "tab"],
"react/jsx-filename-extension": 0,
"no-unused-vars": 1,
"no-trailing-spaces": 1,
"import/named": 0,
"import/default": 0,
"import/namespace": 0,
Expand Down
19 changes: 16 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,34 @@
"coveralls": "^2.11.14",
"eslint": "~3.10.2",
"eslint-config-airbnb": "^13.0.0",
"eslint-config-binary": "^1.0.2",
"eslint-config-prettier": "^1.7.0",
"eslint-loader": "^1.6.0",
"eslint-plugin-import": "^2.0.1",
"eslint-plugin-jsx-a11y": "^2.2.3",
"eslint-plugin-react": "^6.4.1",
"husky": "^0.13.3",
"jest-cli": "^17.0.3",
"lint-staged": "^3.4.0",
"prettier": "^1.2.2",
"prettier-eslint-cli": "^3.3.0",
"rimraf": "^2.5.4",
"webpack": "^2.1.0-beta.23",
"ws": "^1.1.1"
},
"scripts": {
"clean": "rimraf lib dist",
"test": "jest",
"test:coverage": "jest --coverage",
"test": "jest --forceExit",
"test:coverage": "jest --forceExit --coverage",
"test:coveralls": "npm run test:coverage && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage",
"start": "webpack --watch",
"test:eslint": "eslint src/*.js src/calls/*.js",
"test:flow": "flow check --all --show-all-errors",
"test:full": "npm run test:eslint && npm run test:coveralls",
"build": "webpack",
"lint": "eslint src",
"prepublish": "webpack"
"prepublish": "webpack",
"precommit": "lint-staged"
},
"repository": {
"type": "git",
Expand All @@ -58,6 +65,12 @@
"transform-flow-strip-types"
]
},
"lint-staged": {
"*.js": [
"prettier-eslint --write",
"git add"
]
},
"dependencies": {
"binary-utils": "^4.21.0",
"rx-lite": "^4.0.8"
Expand Down
33 changes: 14 additions & 19 deletions src/ApiState.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
const getInitialState = () => ({
token: undefined,
balance: false,
contracts: new Set(),
allContract: false,
transactions: false,
ticks: new Set(),
ticksHistory: new Map(),
candlesHistory: new Map(),
proposals: new Set(),
token : undefined,
balance : false,
contracts : new Set(),
allContract : false,
transactions : false,
ticks : new Set(),
ticksHistory : new Map(),
candlesHistory : new Map(),
proposals : new Set(),
streamIdMapping: new Map(),
});

Expand All @@ -26,7 +26,6 @@ export default class ApiState {
this.state.token = token;
};


subscribeToBalance = () => {
this.state.balance = true;
};
Expand All @@ -35,7 +34,6 @@ export default class ApiState {
this.state.balance = false;
};


subscribeToOpenContract = (contractId: string, streamId: string) => {
if (streamId) {
this.state.contracts.add(contractId);
Expand All @@ -46,13 +44,12 @@ export default class ApiState {
unsubscribeFromAllProposalsOpenContract = () => {
this.state.contracts.clear();
this.state.allContract = false;
}
};

subscribeToAllOpenContracts = () => {
this.state.allContract = true;
};


subscribeToTransactions = () => {
this.state.transactions = true;
};
Expand All @@ -61,7 +58,6 @@ export default class ApiState {
this.state.transactions = false;
};


subscribeToTick = (symbol: string) => {
this.state.ticks.add(symbol);
};
Expand All @@ -73,11 +69,11 @@ export default class ApiState {
unsubscribeFromAllTicks = () => {
this.state.ticks.clear();
this.state.ticksHistory.clear();
}
};

unsubscribeFromAllCandles = () => {
this.state.candlesHistory.clear();
}
};

getTickHistory = (symbol: string, params: Object) => {
if (params && params.subscribe === 1) {
Expand All @@ -100,16 +96,15 @@ export default class ApiState {
this.state.proposals.clear();
};


// special care needed to forget subscription, as backends rely on
// and id instead of more natural keys like symbol and payload
unsubscribeByID = (id) => {
unsubscribeByID = id => {
this.state.streamIdMapping.forEach((payload, streamId) => {
if (streamId === id) {
this.state.contracts.delete(payload);
this.state.proposals.delete(payload);
}
});
this.state.streamIdMapping.delete(id);
}
};
}
80 changes: 47 additions & 33 deletions src/LiveApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,34 @@ let WebSocket = typeof window !== 'undefined' ? window.WebSocket : MockWebSocket

const shouldIgnoreError = (error: Error): boolean =>
error.message.includes('You are already subscribed to') ||
error.message.includes('Input validation failed: forget');
error.message.includes('Input validation failed: forget');

export default class LiveApi {

token: string;
apiUrl: string;
language: string;
appId: number;
brand: string;
socket: WebSocket;
bufferedSends: Object[];
bufferedExecutes: (() => void)[];
bufferedExecutes: () => void[];
unresolvedPromises: Object;
events: LiveEvents;
onAuth: () => void;
apiState: ApiState;

constructor(initParams: InitParams) {
const { apiUrl = defaultApiUrl, language = 'en', appId = 0, brand = '',
sendSpy = () => {}, websocket, connection, keepAlive, useRx = false } = initParams || {};
const {
apiUrl = defaultApiUrl,
language = 'en',
appId = 0,
brand = '',
sendSpy = () => {},
websocket,
connection,
keepAlive,
useRx = false,
} = initParams || {};

this.apiUrl = apiUrl;
this.language = language;
Expand Down Expand Up @@ -71,14 +79,11 @@ export default class LiveApi {

bindCallsAndStateMutators(): void {
Object.keys(calls).forEach(callName => {
this[callName] =
(...params) => this.sendAndUpdateState(callName, ...params);
}
);
this[callName] = (...params) => this.sendAndUpdateState(callName, ...params);
});

Object.keys(customCalls).forEach(callName => {
this[callName] = (...params) =>
customCalls[callName](this, ...params); // seems to be a good place to do some simple cache
this[callName] = (...params) => customCalls[callName](this, ...params); // seems to be a good place to do some simple cache
});
}

Expand Down Expand Up @@ -107,17 +112,26 @@ export default class LiveApi {
onOpen = (): void => {
this.resubscribe();
this.executeBufferedExecutes();
}
};

disconnect = (): void => {
this.token = '';
this.socket.onclose = nullFunc;
this.socket.close();
}
};

resubscribe = (): void => {
const { token, contracts, balance, allContract, candlesHistory,
transactions, ticks, ticksHistory, proposals } = this.apiState.getState();
const {
token,
contracts,
balance,
allContract,
candlesHistory,
transactions,
ticks,
ticksHistory,
proposals,
} = this.apiState.getState();

this.onAuth = () => {
if (balance) {
Expand Down Expand Up @@ -154,7 +168,7 @@ export default class LiveApi {
// ticksHistory, candlesHistory and proposals
this.sendBufferedSends();
}
}
};

changeLanguage = (ln: string): void => {
if (ln === this.language) {
Expand All @@ -164,24 +178,24 @@ export default class LiveApi {
this.socket.close();
this.language = ln;
this.connect();
}
};

isReady = (): boolean =>
!!this.socket && this.socket.readyState === 1;
isReady = (): boolean => !!this.socket && this.socket.readyState === 1;

sendBufferedSends = (): void => {
if (this.isReady()) { // TODO: test fail without this check, find out why!!??
if (this.isReady()) {
// TODO: test fail without this check, find out why!!??
while (this.bufferedSends.length > 0) {
this.bufferedSends.shift()();
}
}
}
};

executeBufferedExecutes = (): void => {
while (this.bufferedExecutes.length > 0) {
this.bufferedExecutes.shift()();
}
}
};

resolvePromiseForResponse = (json: Object): LivePromise => {
if (typeof json.req_id === 'undefined') {
Expand All @@ -205,7 +219,7 @@ export default class LiveApi {
}

return Promise.resolve();
}
};

publishToObservables = (json: Object): void => {
if (typeof json.req_id === 'undefined') {
Expand Down Expand Up @@ -239,7 +253,7 @@ export default class LiveApi {
streamObs.onError(new ServerError(json));
}
}
}
};

onMessage = (message: MessageEvent): LivePromise => {
const json = JSON.parse(message.data);
Expand All @@ -262,7 +276,7 @@ export default class LiveApi {
}

return this.resolvePromiseForResponse(json);
}
};

generatePromiseOrObservable = (json: Object): LivePromise => {
const reqId = json.req_id.toString();
Expand All @@ -285,13 +299,13 @@ export default class LiveApi {

const published = obs.publish();

return published; // use hot observables
return published; // use hot observables
}

return new Promise((resolve, reject) => {
this.unresolvedPromises[reqId] = { resolve, reject };
});
}
};

sendAndUpdateState = (callName: string, ...param: Object): ?LivePromise => {
const reqId = getUniqueId();
Expand Down Expand Up @@ -339,15 +353,15 @@ export default class LiveApi {
}

return undefined;
}
};

execute = (func: () => void): void => {
if (this.isReady()) {
func();
} else {
this.bufferedExecutes.push(func);
}
}
};

// TODO: should we deprecate this? preserve for backward compatibility
send = (json: Object): ?LivePromise => {
Expand All @@ -357,14 +371,14 @@ export default class LiveApi {
req_id: reqId,
...json,
});
}
};

// TODO: should we deprecate this? preserve for backward compatibility
sendRaw = (json: Object): ?LivePromise => {
console.warn('This method is deprecated, use high-level methods'); // eslint-disable-line
const socketSend = () => {
this.sendSpy(JSON.stringify(json));
this.socket.send(JSON.stringify(json));
this.sendSpy(JSON.stringify(json));
this.socket.send(JSON.stringify(json));
};
if (this.isReady()) {
socketSend();
Expand All @@ -377,5 +391,5 @@ export default class LiveApi {
}

return undefined;
}
};
}
Loading