import { INote , IPageCountByContact , IRootAction } from '@models' ; import * as types from './types' ; export interface INotesState { [ noteId ] : INote ; } export interface INotesGetByContactState { error : Error ; isFetching : boolean ; lastUpdated : number ; fetchedPageCount : IPageCountByContact ; } const getByContactInitialState = { error : null , isFetching : false , lastUpdated : null , fetchedPageCount : { } , } ; export const notesReducer = ( state = { } , action ) : INotesState => { let notes ; switch ( action . type ) { case types . GET_NOTES_BY_CONTACT_SUCCESS : notes = { ... state } ; action . payload . notes . forEach ( item => { if ( ! notes [ item . id ] ) { notes [ item . id ] = item ; } } ) ; return notes ; case types . UPDATE_NOTE : notes = { ... state } ; notes [ action . payload . id ] = { ... action . payload , } ; return notes ; case types . ADD_NOTE : notes = { ... state } ; notes [ action . payload . id ] = { ... action . payload , } ; return notes ; case types . UPDATE_NOTE_ID : notes = { ... state } ; notes [ action . payload . newId ] = { ... notes [ action . payload . noteId ] , id : action . payload . newId , } ; notes [ action . payload . noteId ] = undefined ; return notes ; case types . DELETE_NOTE : notes = { ... state } ; notes [ action . payload . id || action . payload . note . id ] = undefined ; return notes ; } return state ; } ; export const getByContactReducer = ( state = getByContactInitialState , action ) : INotesGetByContactState => { switch ( action . type ) { case types . GET_NOTES_BY_CONTACT_FETCHED : return { ... state , error : null , isFetching : true , fetchedPageCount : { [ action . payload . contactId ] : ( state . fetchedPageCount [ action . payload . contactId ] || 0 ) + 1 , } , } ; case types . GET_NOTES_BY_CONTACT_SUCCESS : return { ... state , isFetching : false , lastUpdated : + new Date ( ) , } ; case types . GET_NOTES_BY_CONTACT_FAILED : return { ... state , isFetching : false , error : action . payload . error , } ; } return state ; } ;