2018-02-20 09:30:36 +00:00
|
|
|
/* @flow */
|
2018-07-30 10:52:13 +00:00
|
|
|
|
2018-09-06 15:04:28 +00:00
|
|
|
import { httpRequest } from 'utils/networkUtils';
|
2018-08-14 13:18:16 +00:00
|
|
|
import { resolveAfter } from 'utils/promiseUtils';
|
2018-08-14 13:11:52 +00:00
|
|
|
import { READY } from 'actions/constants/localStorage';
|
2018-02-20 09:30:36 +00:00
|
|
|
|
2018-07-30 10:52:13 +00:00
|
|
|
import type {
|
2018-04-16 21:19:50 +00:00
|
|
|
Middleware,
|
|
|
|
MiddlewareAPI,
|
|
|
|
MiddlewareDispatch,
|
|
|
|
Dispatch,
|
|
|
|
Action,
|
|
|
|
AsyncAction,
|
2018-07-30 10:52:13 +00:00
|
|
|
GetState,
|
2018-08-14 12:56:47 +00:00
|
|
|
} from 'flowtype';
|
2018-04-16 21:19:50 +00:00
|
|
|
|
|
|
|
export const RATE_UPDATE: 'rate__update' = 'rate__update';
|
|
|
|
|
|
|
|
export type FiatRateAction = {
|
|
|
|
type: typeof RATE_UPDATE;
|
|
|
|
network: string;
|
|
|
|
rate: any;
|
|
|
|
}
|
2018-02-20 09:30:36 +00:00
|
|
|
|
2018-07-30 10:52:13 +00:00
|
|
|
const loadRateAction = (): AsyncAction => async (dispatch: Dispatch, getState: GetState): Promise<void> => {
|
2018-09-23 06:31:33 +00:00
|
|
|
const { config } = getState().localStorage;
|
2018-07-30 10:52:13 +00:00
|
|
|
if (!config) return;
|
2018-04-16 21:19:50 +00:00
|
|
|
|
2018-07-30 10:52:13 +00:00
|
|
|
try {
|
2018-09-23 06:31:33 +00:00
|
|
|
config.fiatValueTickers.forEach(async (ticker) => {
|
2018-07-30 10:52:13 +00:00
|
|
|
// const rate: ?Array<any> = await JSONRequest(`${ticker.url}?convert=USD`, 'json');
|
|
|
|
const rate: ?Array<any> = await httpRequest(`${ticker.url}?convert=USD`, 'json');
|
|
|
|
if (rate) {
|
|
|
|
dispatch({
|
|
|
|
type: RATE_UPDATE,
|
|
|
|
network: ticker.network,
|
|
|
|
rate: rate[0],
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
// ignore error
|
2018-02-20 09:30:36 +00:00
|
|
|
}
|
2018-07-30 10:52:13 +00:00
|
|
|
|
|
|
|
await resolveAfter(50000);
|
|
|
|
};
|
2018-02-20 09:30:36 +00:00
|
|
|
|
|
|
|
/**
|
2018-07-30 10:52:13 +00:00
|
|
|
* Middleware
|
2018-02-20 09:30:36 +00:00
|
|
|
*/
|
2018-04-16 21:19:50 +00:00
|
|
|
const CoinmarketcapService: Middleware = (api: MiddlewareAPI) => (next: MiddlewareDispatch) => (action: Action): Action => {
|
2018-03-08 16:10:53 +00:00
|
|
|
next(action);
|
|
|
|
|
2018-04-16 21:19:50 +00:00
|
|
|
if (action.type === READY) {
|
2018-07-30 10:52:13 +00:00
|
|
|
api.dispatch(loadRateAction());
|
2018-02-20 09:30:36 +00:00
|
|
|
}
|
2018-04-16 21:19:50 +00:00
|
|
|
|
|
|
|
return action;
|
2018-02-20 09:30:36 +00:00
|
|
|
};
|
|
|
|
|
2018-04-16 21:19:50 +00:00
|
|
|
export default CoinmarketcapService;
|