Skip to content

Commit

Permalink
feat(entity): add selector to select entity by id
Browse files Browse the repository at this point in the history
* add a new selector 'selectById' to EntitySelector (model)
* implement selector, function to take id string || number
* add tests

See: ngrx#1156
  • Loading branch information
mgred committed Jul 12, 2018
1 parent 2cb81d8 commit c3faa26
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
12 changes: 12 additions & 0 deletions modules/entity/spec/state_selectors.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ describe('Entity State Selectors', () => {

expect(total).toEqual(3);
});

it('should create a selector for selecting an entity by id', () => {
const entity = selectors.selectById('tgg')(state);

expect(entity).toEqual(TheGreatGatsby);
});
});

describe('Uncomposed Selectors', () => {
Expand Down Expand Up @@ -100,5 +106,11 @@ describe('Entity State Selectors', () => {

expect(total).toEqual(3);
});

it('should create a selector for selecting an entity by id', () => {
const entity = selectors.selectById('tgg')(state);

expect(entity).toEqual(TheGreatGatsby);
});
});
});
1 change: 1 addition & 0 deletions modules/entity/src/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export type EntitySelectors<T, V> = {
selectEntities: (state: V) => Dictionary<T>;
selectAll: (state: V) => T[];
selectTotal: (state: V) => number;
selectById: (state: V) => T;
};

export interface EntityAdapter<T> extends EntityStateAdapter<T> {
Expand Down
5 changes: 5 additions & 0 deletions modules/entity/src/state_selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export function createSelectorsFactory<T>() {
(ids: T[], entities: Dictionary<T>): any =>
ids.map((id: any) => (entities as any)[id])
);
const selectById = (id: string | number) =>
createSelector(selectEntities, (entities: Dictionary<T>) => entities[id]);

const selectTotal = createSelector(selectIds, ids => ids.length);

Expand All @@ -26,6 +28,7 @@ export function createSelectorsFactory<T>() {
selectEntities,
selectAll,
selectTotal,
selectById,
};
}

Expand All @@ -34,6 +37,8 @@ export function createSelectorsFactory<T>() {
selectEntities: createSelector(selectState, selectEntities),
selectAll: createSelector(selectState, selectAll),
selectTotal: createSelector(selectState, selectTotal),
selectById: (id: string | number) =>
createSelector(selectState, selectById(id)),
};
}

Expand Down

0 comments on commit c3faa26

Please sign in to comment.