2018-02-20 09:30:36 +00:00
|
|
|
/* @flow */
|
2018-07-30 10:52:13 +00:00
|
|
|
|
2018-02-20 09:30:36 +00:00
|
|
|
|
2018-04-16 21:19:50 +00:00
|
|
|
import { JSONRequest, httpRequest } from '../utils/networkUtils';
|
2018-02-20 09:30:36 +00:00
|
|
|
import { resolveAfter } from '../utils/promiseUtils';
|
2018-04-16 21:19:50 +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,
|
|
|
|
State,
|
|
|
|
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
|
|
|
import type { Config, FiatValueTicker } from '../reducers/LocalStorageReducer';
|
|
|
|
|
|
|
|
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> => {
|
|
|
|
const config: ?Config = getState().localStorage.config;
|
|
|
|
if (!config) return;
|
2018-04-16 21:19:50 +00:00
|
|
|
|
2018-07-30 10:52:13 +00:00
|
|
|
try {
|
|
|
|
config.fiatValueTickers.forEach(async (ticker: FiatValueTicker) => {
|
|
|
|
// 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;
|