UNPKG

1.87 kBPlain TextView Raw
1import { createDraftSafeSelector } from '../createDraftSafeSelector'
2import type {
3 EntityState,
4 EntitySelectors,
5 Dictionary,
6 EntityId,
7} from './models'
8
9export function createSelectorsFactory<T>() {
10 function getSelectors(): EntitySelectors<T, EntityState<T>>
11 function getSelectors<V>(
12 selectState: (state: V) => EntityState<T>
13 ): EntitySelectors<T, V>
14 function getSelectors(
15 selectState?: (state: any) => EntityState<T>
16 ): EntitySelectors<T, any> {
17 const selectIds = (state: any) => state.ids
18
19 const selectEntities = (state: EntityState<T>) => state.entities
20
21 const selectAll = createDraftSafeSelector(
22 selectIds,
23 selectEntities,
24 (ids: readonly T[], entities: Dictionary<T>): any =>
25 ids.map((id: any) => (entities as any)[id])
26 )
27
28 const selectId = (_: any, id: EntityId) => id
29
30 const selectById = (entities: Dictionary<T>, id: EntityId) => entities[id]
31
32 const selectTotal = createDraftSafeSelector(selectIds, (ids) => ids.length)
33
34 if (!selectState) {
35 return {
36 selectIds,
37 selectEntities,
38 selectAll,
39 selectTotal,
40 selectById: createDraftSafeSelector(
41 selectEntities,
42 selectId,
43 selectById
44 ),
45 }
46 }
47
48 const selectGlobalizedEntities = createDraftSafeSelector(
49 selectState,
50 selectEntities
51 )
52
53 return {
54 selectIds: createDraftSafeSelector(selectState, selectIds),
55 selectEntities: selectGlobalizedEntities,
56 selectAll: createDraftSafeSelector(selectState, selectAll),
57 selectTotal: createDraftSafeSelector(selectState, selectTotal),
58 selectById: createDraftSafeSelector(
59 selectGlobalizedEntities,
60 selectId,
61 selectById
62 ),
63 }
64 }
65
66 return { getSelectors }
67}