import Immutable from 'immutable' ; import { IFeed , IFeedsState , IIFeedsState , IReduxAction } from '../../schemas' ; import { FeedsActionTypes , IAddFeedPayload , ISetFeedFaviconPayload , ISetFeedsPayload , } from '../actions' ; const initialFeedsState = Immutable . Record < IFeedsState > ( { isCreating : false , isUpdating : false , list : Immutable . List < IFeed > ( [ ] ) , map : Immutable . Map < IFeed > ( { } ) , } ) ( ) ; Object . defineProperty ( window , 'Immutable' , { value : Immutable } ) ; const feedsReducer = ( state = initialFeedsState , action ) => { const payload = action . payload ; switch ( action . type ) { case FeedsActionTypes . SET_IS_UPDATING_FEEDS : return state . set ( 'isUpdating' , action . payload . isUpdating ) ; case FeedsActionTypes . SET_IS_CREATING_FEED : return state . set ( 'isCreating' , action . payload . isCreating ) ; case FeedsActionTypes . SET_FEED_FAVICON : return handleSetFeedFavicon ( state , payload ) ; case FeedsActionTypes . ADD_FEED : return handleAddFeed ( state , payload ) ; case FeedsActionTypes . SET_FEEDS : return handleSetFeeds ( state , payload ) ; default : return state ; } } ; function handleSetFeedFavicon ( state , payload ) { return state . update ( 'map' , ( map ) => map . update ( payload . feedId , ( feed ) => { const newFeed = { ... feed } ; newFeed . favicon = payload . favicon ; return newFeed ; } ) ) ; } function handleAddFeed ( state , payload ) { const feed = payload . feed ; return state . update ( 'map' , ( map ) => { return map . set ( feed . _id , feed ) ; } ) . update ( 'list' , ( list ) => { return list . push ( feed ) ; } ) ; } function handleSetFeeds ( state , payload ) { const feeds = payload . feeds ; const map = { } ; feeds . forEach ( ( feed ) => { map [ feed . _id ] = feed ; } ) ; return state . set ( 'list' , Immutable . List ( feeds ) ) . set ( 'map' , Immutable . Map ( map ) ) ; } export default feedsReducer ;