Skip to content

Commit

Permalink
Merge branch 'master' into user-defined-type-guards
Browse files Browse the repository at this point in the history
  • Loading branch information
fb55 authored Apr 10, 2018
2 parents 8b2e5da + 5987fa9 commit 5226f0b
Show file tree
Hide file tree
Showing 21 changed files with 59 additions and 61 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"@types/commander": "2.3.31",
"@types/crypto-js": "3.1.32",
"@types/nock": "8.2.0",
"@types/node": "6.0.51",
"@types/node": "7.0.58",
"@types/query-string": "3.0.30",
"@types/simple-mock": "0.0.27",
"@types/superagent": "2.0.35",
Expand Down
4 changes: 2 additions & 2 deletions src/FXService/FXProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,13 @@ export abstract class FXProvider {
return this.supportsPair(inversePair).then<FXObject>((inverseOk: boolean) => {
if (inverseOk) {
return this.getPromiseForRate(inversePair).then((inverse: FXObject) => {
const rate = {
const rate: FXObject = {
from: pair.from,
to: pair.to,
rate: ONE.div(inverse.rate),
time: inverse.time
};
return Promise.resolve<FXObject>(rate);
return rate;
});
} else {
return Promise.reject(new EFXRateUnavailable(`Currency pair ${pair.from}-${pair.to} or its inverse is not supported`, this.name));
Expand Down
13 changes: 6 additions & 7 deletions src/FXService/FXService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export class FXService extends EventEmitter {
/**
* Replaces the [[FXRateCalculator]] instance and returns `this` so that you can chain setter calls.
*/
setCalculator(value: FXRateCalculator) {
setCalculator(value: FXRateCalculator): this {
this._calculator = value;
return this;
}
Expand All @@ -88,7 +88,7 @@ export class FXService extends EventEmitter {
/**
* Sets a logger for the service and returns `this` so that you can chain setter calls.
*/
setLogger(value: Logger) {
setLogger(value: Logger): this {
this._logger = value;
return this;
}
Expand All @@ -103,7 +103,7 @@ export class FXService extends EventEmitter {
/**
* Assigns a new polling interval for calculating exchange rates (in ms). Returns `this` so that you can chain setter calls.
*/
setRefreshInterval(value: number) {
setRefreshInterval(value: number): this {
this._refreshInterval = value;
if (this.timer) {
clearInterval(this.timer);
Expand All @@ -124,7 +124,7 @@ export class FXService extends EventEmitter {
/**
* Replace all current pairs with the array of pairs provided. Returns `this` so that you can chain setter calls.
*/
setActivePairs(pairs: CurrencyPair[]) {
setActivePairs(pairs: CurrencyPair[]): this {
this._currencyPairs = [];
pairs.forEach((pair) => this.addCurrencyPair(pair));
return this;
Expand All @@ -134,7 +134,7 @@ export class FXService extends EventEmitter {
* Adds a single currency pair to the service without removing any that are already being queried. If the pair is already
* in the list, this function has no effect. Returns `this` so that you can chain setter calls.
*/
addCurrencyPair(pair: CurrencyPair) {
addCurrencyPair(pair: CurrencyPair): this {
if (this.indexOf(pair) >= 0) {
return this;
}
Expand Down Expand Up @@ -228,7 +228,6 @@ export class FXService extends EventEmitter {
this._rates[index] = Object.assign({ change: change }, rate);
});
this.errorState = false;
return Promise.resolve();
}, (err: Error) => {
this.log('warn', 'An error occurred fetching latest exchange rates', err.message);
this.errorState = true;
Expand All @@ -239,7 +238,7 @@ export class FXService extends EventEmitter {
// because we emit a message above, client errors will be caught and returned here.
this.log('error', 'A client error has caused an FXUpdate failure', err);
this.errorState = true;
return Promise.resolve(null);
return null;
});
}
}
2 changes: 1 addition & 1 deletion src/FXService/calculators/RobustCalculator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export class RobustCalculator extends FXRateCalculator {
rate: rate && Big(rate),
change: null
};
return Promise.resolve(result);
return result;
});
}

Expand Down
3 changes: 1 addition & 2 deletions src/FXService/providers/CoinMarketCapProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,11 @@ export default class CoinMarketCapProvider extends FXProvider {
REVERSE_MAP[currency.id] = currency.symbol;
SUPPORTED_BASE_CURRENCIES.push(currency.symbol);
});
return Promise.resolve();
});
this.initializing = initCodeMap;
}
return initCodeMap.then(() => {
return Promise.resolve(SUPPORTED_BASE_CURRENCIES.includes(pair.from));
return SUPPORTED_BASE_CURRENCIES.includes(pair.from);
});
}

Expand Down
2 changes: 1 addition & 1 deletion src/FXService/providers/OpenExchangeProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export default class OpenExchangeProvider extends FXProvider {
.then((res: Response) => {
const curs: { [cur: string]: string } = res.body;
supportedCurrencies = Object.keys(curs);
return Promise.resolve(isSupported(pair));
return isSupported(pair);
});
}

Expand Down
8 changes: 4 additions & 4 deletions src/FXService/providers/YahooFXProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default class YahooFinanceFXProvider extends FXProvider {
SUPPORTED_PAIRS.push(tag.slice(0, tag.length - 2));
}
});
return Promise.resolve(this.isSupportedPair(pair));
return this.isSupportedPair(pair);
}, (err: Error) => Promise.reject(err));
}

Expand All @@ -73,12 +73,12 @@ export default class YahooFinanceFXProvider extends FXProvider {
} catch (err) {
return Promise.reject(error);
}
return Promise.resolve<FXObject>({
const r: FXObject = {
time: new Date(created),
from: pair.from,
to: pair.to,
rate: Big(rate)
});
rate: Big(rate)};
return r;
}, (result: Response) => {
let details = {};
try {
Expand Down
6 changes: 3 additions & 3 deletions src/core/Triggers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,18 @@ export class Trigger<T extends StreamMessage> {
this.feed = feed;
}

setAction(action: Action<T>): Trigger<T> {
setAction(action: Action<T>): this {
this.action = action;
return this;
}

setFilter(filter: TriggerFilter): Trigger<T> {
setFilter(filter: TriggerFilter): this {
this.filter = filter;
this.feed.on('data', filter);
return this;
}

execute(event: T): Trigger<T> {
execute(event: T): this {
this.action(event);
return this;
}
Expand Down
2 changes: 1 addition & 1 deletion src/exchanges/bittrex/BittrexFeed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export class BittrexFeed extends ExchangeFeed {
});
})).then(() => {
// Every result is guaranteed to be true
return Promise.resolve(true);
return true;
}).catch((err) => {
return Promise.reject(err);
});
Expand Down
24 changes: 12 additions & 12 deletions src/exchanges/ccxt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,17 +161,17 @@ export default class CCXTExchangeWrapper implements PublicExchangeAPI, Authentic
for (const id in markets) {
const m: CCXTMarket = markets[id];
if (m.base === base && m.quote === quote) {
return Promise.resolve(m.symbol);
return m.symbol;
}
}
return Promise.resolve(null);
return null;
}).catch((err: Error) => rejectWithError(`Error loading symbols for ${gdaxProduct} on ${this.instance.name} (CCXT)`, err));
}

loadProducts(): Promise<Product[]> {
return this.instance.loadMarkets(true).then((markets: ccxt.CCXTMarket[]) => {
if (!markets) {
return Promise.resolve([]);
return [];
}
const result: Product[] = [];
for (const id in markets) {
Expand All @@ -188,7 +188,7 @@ export default class CCXTExchangeWrapper implements PublicExchangeAPI, Authentic
};
result.push(product);
}
return Promise.resolve(result);
return result;
}).catch((err: Error) => rejectWithError(`Error loading products on ${this.instance.name} (CCXT)`, err));
}

Expand Down Expand Up @@ -222,7 +222,7 @@ export default class CCXTExchangeWrapper implements PublicExchangeAPI, Authentic
};
addSide('buy', ccxtBook.bids);
addSide('sell', ccxtBook.asks);
return Promise.resolve(book);
return book;
}).catch((err: Error) => rejectWithError(`Error loading order book for ${gdaxProduct} on ${this.instance.name} (CCXT)`, err));
}

Expand All @@ -231,7 +231,7 @@ export default class CCXTExchangeWrapper implements PublicExchangeAPI, Authentic
return this.instance.fetchTicker(id);
}).then((ticker: any) => {
if (!ticker) {
return Promise.resolve(null);
return null;
}
const t: Ticker = {
productId: gdaxProduct,
Expand All @@ -241,7 +241,7 @@ export default class CCXTExchangeWrapper implements PublicExchangeAPI, Authentic
bid: Big(ticker.ask),
volume: Big(ticker.baseVolume)
};
return Promise.resolve(t);
return t;
}).catch((err: Error) => rejectWithError(`Error loading ticker for ${gdaxProduct} on ${this.instance.name} (CCXT)`, err));
}

Expand All @@ -266,14 +266,14 @@ export default class CCXTExchangeWrapper implements PublicExchangeAPI, Authentic
volume: Big(d[5])
};
});
return Promise.resolve(candles);
return candles;
}).catch((err: Error) => rejectWithError(`Error loading candles for ${product} on ${this.instance.name} (CCXT)`, err));
}

placeOrder(order: PlaceOrderMessage): Promise<LiveOrder> {
return this.getSourceSymbol(order.productId).then((id: string) => {
if (!id) {
return Promise.resolve(null);
return null;
}
const args = Object.assign({postOnly: order.postOnly, funds: order.funds, clientId: order.clientId}, order.extra);
return this.instance.createOrder(id, order.orderType, order.side, order.size.toString(), order.price.toString(), args).then((res: any) => {
Expand All @@ -287,7 +287,7 @@ export default class CCXTExchangeWrapper implements PublicExchangeAPI, Authentic
extra: res.info,
status: 'active'
};
return Promise.resolve(result);
return result;
}).catch((err: Error) => rejectWithError(`Error placing order for ${order.productId} on ${this.instance.name} (CCXT)`, err));
});

Expand Down Expand Up @@ -315,7 +315,7 @@ export default class CCXTExchangeWrapper implements PublicExchangeAPI, Authentic
}
return this.instance.fetchBalance().then((balances: any) => {
if (!balances) {
return Promise.resolve(null);
return null;
}
const result: Balances = {default: {}};
for (const cur in balances) {
Expand All @@ -329,7 +329,7 @@ export default class CCXTExchangeWrapper implements PublicExchangeAPI, Authentic
available: isFinite(available) ? Big(available) : null
};
}
return Promise.resolve(result);
return result;
}).catch((err: Error) => rejectWithError(`Error loading balances on ${this.instance.name} (CCXT)`, err));
}

Expand Down
12 changes: 5 additions & 7 deletions src/exchanges/gdax/GDAXExchangeAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,17 +259,15 @@ export class GDAXExchangeAPI implements PublicExchangeAPI, AuthenticatedExchange
cancelOrder(id: string): Promise<string> {
const apiCall = this.authCall('DELETE', `/orders/${id}`, {});
return this.handleResponse<string[]>(apiCall, {order_id: id}).then((ids: string[]) => {
return Promise.resolve(ids[0]);
return ids[0];
});

}

cancelAllOrders(product: string): Promise<string[]> {
const apiCall = this.authCall('DELETE', `/orders`, {});
const options = product ? {product_id: product} : null;
return this.handleResponse<string[]>(apiCall, options).then((ids: string[]) => {
return Promise.resolve(ids);
});
return this.handleResponse<string[]>(apiCall, options);
}

loadOrder(id: string): Promise<LiveOrder> {
Expand Down Expand Up @@ -341,7 +339,7 @@ export class GDAXExchangeAPI implements PublicExchangeAPI, AuthenticatedExchange
if (opts.headers) {
req = req.set(opts.headers);
}
return Promise.resolve(req);
return req;
});
}

Expand All @@ -363,7 +361,7 @@ export class GDAXExchangeAPI implements PublicExchangeAPI, AuthenticatedExchange
handleResponse<T>(req: Promise<Response>, meta: any): Promise<T> {
return req.then((res: Response) => {
if (res.status >= 200 && res.status < 300) {
return Promise.resolve(res.body);
return res.body;
}
const err: HTTPError = new HTTPError(`Error handling GDAX request for ${(req as any).url}`, res);
return Promise.reject(err);
Expand Down Expand Up @@ -444,7 +442,7 @@ export class GDAXExchangeAPI implements PublicExchangeAPI, AuthenticatedExchange
}
return this.authClient.getCoinbaseAccounts().then((accounts: CoinbaseAccount[]) => {
this.coinbaseAccounts = accounts;
return Promise.resolve(accounts);
return accounts;
}).catch((err: GDAXHTTPError) => {
return Promise.reject(new HTTPError('Error loading Coinbase accounts', extractResponse(err.response)));
});
Expand Down
4 changes: 2 additions & 2 deletions src/exchanges/poloniex/PoloniexCommon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,13 @@ export function getProductInfo(id: number, refresh: boolean, logger?: Logger): P
products.forEach((p: Product) => {
productInfo[p.sourceData.id] = p;
});
return Promise.resolve(productInfo[id]);
return productInfo[id];
});
}

export function getAllProductInfo(refresh: boolean, logger?: Logger): Promise<PoloniexProducts> {
return getProductInfo(0, refresh, logger).then(() => {
return Promise.resolve(productInfo);
return productInfo;
});
}

Expand Down
2 changes: 1 addition & 1 deletion src/exchanges/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { extractResponse, HTTPError } from '../lib/errors';
export function handleResponse<T>(req: Promise<Response>, meta: any): Promise<T> {
return req.then<T>((res: Response) => {
if (res.status >= 200 && res.status < 300) {
return Promise.resolve<T>(res.body as T);
return res.body as T;
}
return Promise.reject(new HTTPError('Error in Bitfinex request', extractResponse(res)));
}).catch((err) => {
Expand Down
2 changes: 1 addition & 1 deletion src/factories/bitfinexFactories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export function FeedFactory(logger: Logger, productIDs?: string[]): Promise<Bitf
.loadProducts()
.then((products: Product[]) => {
const ids = products.map((p) => p.id);
return Promise.resolve(ids);
return ids;
});
}
return productPromise.then((productIds: string[]) => {
Expand Down
2 changes: 1 addition & 1 deletion src/factories/gdaxFactories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export function FeedFactory(logger: Logger, productIDs?: string[], auth?: GDAXAu
.loadProducts()
.then((products: Product[]) => {
const ids = products.map((p) => p.id);
return Promise.resolve(ids);
return ids;
});
}
return productPromise.then((productIds: string[]) => {
Expand Down
2 changes: 1 addition & 1 deletion src/samples/ccxtDemo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ for (let i = 0; i < 5; i++) {
api.loadProducts().then((products) => {
product = randomElement(products);
if (!product) {
return Promise.resolve(null);
return null;
}
console.log(`Loading ticker for ${product.id} on ${api.owner}`);
return api.loadTicker(product.id);
Expand Down
4 changes: 2 additions & 2 deletions src/utils/promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ export function delay(time: number): Promise<void> {
/**
* Apply each argument in arr to iteratorFn, waiting for the promise to resolve before continuing
*/
export function eachSeries<T>(arr: T[], iteratorFn: (arg: T) => Promise<any>) {
export function eachSeries<T, U>(arr: T[], iteratorFn: (arg: T) => Promise<U>): Promise<null | U> {
return arr.reduce((prev, item) => {
return prev.then(() => {
return iteratorFn(item);
});
}, Promise.resolve());
}, Promise.resolve(null));
}

/**
Expand Down
Loading

0 comments on commit 5226f0b

Please sign in to comment.