import { reducerWithInitialState } from 'typescript-fsa-reducers' import { combineReducers } from 'redux' import { keyBy } from 'lodash' import { IEnrichmentPayload, IStatusByEmailState, IProfileByEmailState, } from './interfaces' import * as actions from './actions' import { Status } from '../../interfaces/status' const profileByEmail = reducerWithInitialState({} as IProfileByEmailState) .case(actions.fetchEnrichmentSuccess, (state, payload) => { const byEmail = keyBy(payload.profiles, profile => profile.email) return Object.assign({}, state, byEmail) }) .case(actions.receiveProfiles, (state, payload) => { const byEmail = keyBy(payload, profile => profile.email) return Object.assign({}, state, byEmail) }) const makeStatusByEmailHandler = (status: Status) => { return (state: IStatusByEmailState, payload: IEnrichmentPayload) => { const byEmail = payload.emails.reduce((acc: { [email: string]: Status }, email) => { acc[email] = status return acc }, {}) return Object.assign({}, state, byEmail) } } const statusByEmail = reducerWithInitialState({} as IStatusByEmailState) .case(actions.fetchEnrichmentPending, makeStatusByEmailHandler(Status.Pending)) .case(actions.fetchEnrichmentSuccess, makeStatusByEmailHandler(Status.Success)) .case(actions.fetchEnrichmentFailure, makeStatusByEmailHandler(Status.Failure)) export default combineReducers({ profileByEmail, statusByEmail, })