File size: 1,433 Bytes
c2b7eb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models'
import { createInitialStateFactory } from './entity_state'
import { createSelectorsFactory } from './state_selectors'
import { createSortedStateAdapter } from './sorted_state_adapter'
import { createUnsortedStateAdapter } from './unsorted_state_adapter'
import type { WithRequiredProp } from '../tsHelpers'

export function createEntityAdapter<T, Id extends EntityId>(
  options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>,
): EntityAdapter<T, Id>

export function createEntityAdapter<T extends { id: EntityId }>(
  options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>,
): EntityAdapter<T, T['id']>

/**
 *
 * @param options
 *
 * @public
 */
export function createEntityAdapter<T>(
  options: EntityAdapterOptions<T, EntityId> = {},
): EntityAdapter<T, EntityId> {
  const {
    selectId,
    sortComparer,
  }: Required<EntityAdapterOptions<T, EntityId>> = {
    sortComparer: false,
    selectId: (instance: any) => instance.id,
    ...options,
  }

  const stateAdapter = sortComparer
    ? createSortedStateAdapter(selectId, sortComparer)
    : createUnsortedStateAdapter(selectId)
  const stateFactory = createInitialStateFactory(stateAdapter)
  const selectorsFactory = createSelectorsFactory<T, EntityId>()

  return {
    selectId,
    sortComparer,
    ...stateFactory,
    ...selectorsFactory,
    ...stateAdapter,
  }
}