/** * External dependencies */ import { isEqual, keyBy } from 'lodash'; import type { AnyAction } from '@nab/types'; /** * Internal dependencies */ import { INIT_STATE } from '../config'; import type { State as FullState } from '../types'; import type { EntityAction as Action } from '../actions/entities'; type State = FullState[ 'entities' ]; export function entities( state = INIT_STATE.entities, action: AnyAction ): State { return actualReducer( state, action as Action ) ?? state; } function actualReducer( state: State, action: Action ): State { switch ( action.type ) { case 'RECEIVE_TYPE_QUERY': { if ( isEqual( state.config, action.kindEntities ) ) { return state; } return { ...state, config: action.kindEntities, }; } case 'RECEIVE_ITEMS': { const newItems = action.items.filter( ( item ) => ! isEqual( state.data[ action.kind ]?.[ item.id ], item ) ); if ( ! newItems.length ) { return state; } return { ...state, data: { ...state.data, [ action.kind ]: { ...state.data[ action.kind ], ...keyBy( newItems, 'id' ), }, }, }; } } }