2017-09-26 03:41:11 +00:00
|
|
|
import { handleJSONResponse } from 'api/utils';
|
|
|
|
|
2017-12-19 22:46:34 +00:00
|
|
|
export const rateSymbols: Symbols = ['USD', 'EUR', 'GBP', 'BTC', 'CHF', 'REP', 'ETH'];
|
|
|
|
|
|
|
|
export type Symbols = (keyof ISymbol)[];
|
2017-09-26 03:41:11 +00:00
|
|
|
// TODO - internationalize
|
|
|
|
const ERROR_MESSAGE = 'Could not fetch rate data.';
|
|
|
|
const CCApi = 'https://min-api.cryptocompare.com';
|
|
|
|
|
2017-11-18 20:15:02 +00:00
|
|
|
const CCRates = (symbols: string[]) => {
|
2017-12-19 22:46:34 +00:00
|
|
|
const tsyms = rateSymbols.concat(symbols as any).join(',');
|
2017-11-18 20:15:02 +00:00
|
|
|
return `${CCApi}/data/price?fsym=ETH&tsyms=${tsyms}`;
|
2017-11-15 05:51:09 +00:00
|
|
|
};
|
2017-09-26 03:41:11 +00:00
|
|
|
|
|
|
|
export interface CCResponse {
|
2017-12-19 22:46:34 +00:00
|
|
|
[symbol: string]: ISymbol;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface ISymbol {
|
|
|
|
USD: number;
|
|
|
|
EUR: number;
|
|
|
|
GBP: number;
|
|
|
|
BTC: number;
|
|
|
|
CHF: number;
|
|
|
|
REP: number;
|
|
|
|
ETH: number;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface IRates extends ISymbol {
|
|
|
|
Response?: 'Error';
|
2017-09-26 03:41:11 +00:00
|
|
|
}
|
|
|
|
|
2017-11-18 20:15:02 +00:00
|
|
|
export const fetchRates = (symbols: string[] = []): Promise<CCResponse> =>
|
|
|
|
fetch(CCRates(symbols))
|
2017-11-15 05:51:09 +00:00
|
|
|
.then(response => handleJSONResponse(response, ERROR_MESSAGE))
|
2017-12-19 22:46:34 +00:00
|
|
|
.then((rates: IRates) => {
|
2017-11-29 19:45:38 +00:00
|
|
|
// API errors come as 200s, so check the json for error
|
|
|
|
if (rates.Response && rates.Response === 'Error') {
|
|
|
|
throw new Error('Failed to fetch rates');
|
|
|
|
}
|
|
|
|
|
2017-11-18 20:15:02 +00:00
|
|
|
// All currencies are in ETH right now. We'll do token -> eth -> value to
|
|
|
|
// do it all in one request
|
|
|
|
// to their respective rates via ETH.
|
|
|
|
return symbols.reduce(
|
2017-12-19 22:46:34 +00:00
|
|
|
(eqRates, sym: keyof ISymbol) => {
|
2017-12-01 20:40:27 +00:00
|
|
|
if (rates[sym]) {
|
2017-12-19 22:46:34 +00:00
|
|
|
eqRates[sym] = rateSymbols.reduce(
|
|
|
|
(symRates, rateSym) => {
|
|
|
|
symRates[rateSym] = 1 / rates[sym] * rates[rateSym];
|
|
|
|
return symRates;
|
|
|
|
},
|
|
|
|
{} as ISymbol
|
|
|
|
);
|
2017-12-01 20:40:27 +00:00
|
|
|
}
|
2017-11-18 20:15:02 +00:00
|
|
|
return eqRates;
|
|
|
|
},
|
|
|
|
{
|
|
|
|
ETH: {
|
|
|
|
USD: rates.USD,
|
|
|
|
EUR: rates.EUR,
|
|
|
|
GBP: rates.GBP,
|
|
|
|
BTC: rates.BTC,
|
|
|
|
CHF: rates.CHF,
|
|
|
|
REP: rates.REP,
|
|
|
|
ETH: 1
|
|
|
|
}
|
2017-12-19 22:46:34 +00:00
|
|
|
} as CCResponse
|
2017-11-18 20:15:02 +00:00
|
|
|
);
|
|
|
|
});
|