Skip to content

Commit

Permalink
improved subscribeorders ExchangeUnion#687
Browse files Browse the repository at this point in the history
  • Loading branch information
sercan committed Jan 7, 2019
1 parent 59aa8ff commit 69ee090
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions lib/cli/commands/subscribeorders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,51 @@ export const builder = {
};

export const handler = (argv: Arguments) => {
ensureConnection(argv, true);
};

const ensureConnection = (argv: Arguments, printError?: boolean) => {
loadXudClient(argv).getInfo(new xudrpc.GetInfoRequest(), (error: Error | null) => {
if (error) {
if (printError) console.error(`${error.name}: ${error.message}`);
setTimeout(ensureConnection.bind(undefined, argv), 3000);
} else {
console.log('Successfully connected, subscribing for orders');
subscribeOrders(argv);
}
});
};

const subscribeOrders = (argv: Arguments) => {
const addedOrdersRequest = new xudrpc.SubscribeAddedOrdersRequest();
addedOrdersRequest.setExisting(argv.existing);
const addedOrdersSubscription = loadXudClient(argv).subscribeAddedOrders(addedOrdersRequest);
addedOrdersSubscription.on('data', (order: xudrpc.Order) => {
console.log(`Order added: ${JSON.stringify(order.toObject())}`);
});

// adding end, close, error events only once,
// since they'll be thrown for three of subscriptions in the corresponding cases, catching once is enough.
addedOrdersSubscription.on('end', ensureConnection.bind(undefined, argv, true));
addedOrdersSubscription.on('close', ensureConnection.bind(undefined, argv, true));
addedOrdersSubscription.on('error', (err: Error) => {
console.log(`Unexpected error occured: ${JSON.stringify(err)}, retrying to connect`);
ensureConnection(argv);
});

const removedOrdersSubscription = loadXudClient(argv).subscribeRemovedOrders(new xudrpc.SubscribeRemovedOrdersRequest());
removedOrdersSubscription.on('data', (orderRemoval: xudrpc.OrderRemoval) => {
console.log(`Order removed: ${JSON.stringify(orderRemoval.toObject())}`);
});

// prevent exiting and do nothing, it's already cached above.
removedOrdersSubscription.on('error', () => {});

const swapsSubscription = loadXudClient(argv).subscribeSwaps(new xudrpc.SubscribeSwapsRequest());
swapsSubscription.on('data', (swapResult: xudrpc.SwapResult) => {
console.log(`Order swapped: ${JSON.stringify(swapResult.toObject())}`);
});

// prevent exiting and do nothing, it's already cached above.
swapsSubscription.on('error', () => {});
};

0 comments on commit 69ee090

Please sign in to comment.