Last active
February 18, 2020 00:37
-
-
Save alexytiger/b9afa7c1dcf1759bb9739bea1c5efb1f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity'; | |
import { createReducer, on } from '@ngrx/store'; | |
import { PurchaseWidgetModel, PurchaseContractModel } from '../../models'; | |
import { PurchaseContractActions } from '../actions'; | |
export interface State extends EntityState<PurchaseWidgetModel> { | |
loaded: boolean; | |
selectedPurchaseContract: PurchaseContractModel; | |
} | |
export function sortByKey(a: PurchaseWidgetModel, b: PurchaseWidgetModel): number | |
{ | |
return a.productKey.localeCompare(b.productKey); | |
} | |
export const adapter: EntityAdapter<PurchaseWidgetModel> = | |
createEntityAdapter<PurchaseWidgetModel>({ | |
selectId: (product: PurchaseWidgetModel) => product.productKey, | |
sortComparer: sortByKey, | |
}); | |
export const initialState: State = adapter.getInitialState({ | |
loaded: false, | |
selectedPurchaseContract: null | |
}); | |
export const reducer = createReducer( | |
initialState, | |
on( | |
PurchaseContractActions.loadProductsSuccess, | |
(state, { products }) => adapter.addAll(products, { | |
...state, | |
loaded: true, | |
selectedPurchaseContract: null | |
}) | |
), | |
on( | |
PurchaseContractActions.removePurchaseContractSuccess, | |
(state, { key }) => adapter.removeOne(key, { | |
...state, | |
selectedPurchaseContract: null | |
}) | |
), | |
/** | |
* The addOne function provided by the created adapter | |
* adds one record to the entity dictionary | |
* and returns a new state including that records if it doesn't | |
* exist already. If the collection is to be sorted, the adapter will | |
* insert the new record into the sorted array. | |
*/ | |
on(PurchaseContractActions.createPurchaseContractSuccess, | |
(state, { product }) => adapter.addOne(product, state)), | |
on(PurchaseContractActions.loadPurchaseContractSuccess, | |
(state, { contract }) => ({ | |
...state, | |
selectedPurchaseContract: contract, | |
})), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment