forked from johnpapa/angular-ngrx-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentity-definition.ts
56 lines (49 loc) · 1.8 KB
/
entity-definition.ts
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
49
50
51
52
53
54
55
56
import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import {
EntitySelectors,
EntitySelectorsFactory
} from '../selectors/entity-selectors';
import { Dictionary, IdSelector, Update } from '../utils/ngrx-entity-models';
import { defaultSelectId } from '../utils/utilities';
import { EntityCollection } from '../reducers/entity-collection';
import { EntityDispatcherOptions } from '../dispatchers/entity-dispatcher';
import { EntityFilterFn } from './entity-filters';
import { EntityMetadata } from './entity-metadata';
export interface EntityDefinition<T = any> {
entityName: string;
entityAdapter: EntityAdapter<T>;
entityDispatcherOptions?: Partial<EntityDispatcherOptions>;
initialState: EntityCollection<T>;
metadata: EntityMetadata<T>;
selectId: IdSelector<T>;
}
export function createEntityDefinition<T, S extends object>(
metadata: EntityMetadata<T, S>
): EntityDefinition<T> {
// extract known essential properties driving entity definition.
let entityName = metadata.entityName;
if (!entityName) {
throw new Error('Missing required entityName');
}
metadata.entityName = entityName = entityName.trim();
const selectId = metadata.selectId || defaultSelectId;
const sortComparer = (metadata.sortComparer = metadata.sortComparer || false);
const entityAdapter = createEntityAdapter<T>({ selectId, sortComparer });
const entityDispatcherOptions: Partial<EntityDispatcherOptions> =
metadata.entityDispatcherOptions || {};
const initialState: EntityCollection<T> = entityAdapter.getInitialState({
filter: '',
loaded: false,
loading: false,
originalValues: {},
...(metadata.additionalCollectionState || {})
});
return {
entityName,
entityAdapter,
entityDispatcherOptions,
initialState,
metadata,
selectId
};
}