import { Observable } from 'rxjs' import { combineEpics, ActionsObservable } from 'redux-observable' import { Store } from 'redux' import * as api from './api' import * as actions from './actions' import * as selectors from './selectors' import * as AuthSelectors from '../auth/selectors' import { fetchUserSuccess } from '../auth/actions' import { User } from '../auth/interfaces' import { IOrg, IOrgProperties, IUser } from './interfaces' const fetchOrg = (action$: ActionsObservable, store: Store) => { return action$.ofType(fetchUserSuccess.toString()) .pluck('payload') .mergeMap((({ orgId }: User) => { const accessToken = AuthSelectors.accessToken(store.getState()) return api.fetchOrg(orgId, accessToken) .map((value: IOrg) => actions.fetchOrgSuccess(value)) .startWith(actions.fetchOrgPending()) .catch(() => { return Observable.of(actions.fetchOrgFailure()) }) })) } const fetchOrgProperties = (action$: ActionsObservable, store: Store) => { return action$.ofType(fetchUserSuccess.toString()) .pluck('payload') .mergeMap((({ orgId }: User) => { const accessToken = AuthSelectors.accessToken(store.getState()) return api.fetchOrgProperties(orgId, accessToken) .map((value: IOrgProperties) => actions.fetchOrgPropertiesSuccess(value)) .startWith(actions.fetchOrgPropertiesPending()) .catch(() => { return Observable.of(actions.fetchOrgPropertiesFailure()) }) })) } const fetchUsers = (action$: ActionsObservable, { getState }: Store) => { return action$ .ofType(actions.fetchOrgSuccess.toString()) .mergeMap(() => { const state = getState() const accessToken = AuthSelectors.accessToken(state) const orgId = selectors.orgId(state) return api .fetchUsers(orgId, accessToken) .map((users: IUser[]) => actions.fetchUsersSuccess(users)) .startWith(actions.fetchUsersPending()) .catch(() => Observable.of(actions.fetchUsersFailed())) }) } export const epic = combineEpics( fetchOrg, fetchOrgProperties, fetchUsers, )