-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
models.ts
93 lines (71 loc) · 2.34 KB
/
models.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
export type ComparerStr<T> = {
(a: T, b: T): string;
};
export type ComparerNum<T> = {
(a: T, b: T): number;
};
export type Comparer<T> = ComparerNum<T> | ComparerStr<T>;
export type IdSelectorStr<T> = {
(model: T): string;
};
export type IdSelectorNum<T> = {
(model: T): number;
};
export type IdSelector<T> = IdSelectorStr<T> | IdSelectorNum<T>;
export type DictionaryNum<T> = {
[id: number]: T;
};
export abstract class Dictionary<T> implements DictionaryNum<T> {
[id: string]: T;
}
export type UpdateStr<T> = {
id: string;
changes: Partial<T>;
};
export type UpdateNum<T> = {
id: number;
changes: Partial<T>;
};
export type Update<T> = UpdateStr<T> | UpdateNum<T>;
export interface EntityState<T> {
ids: any[];
entities: Dictionary<T>;
}
export interface EntityDefinition<T> {
selectId: IdSelector<T>;
sortComparer: false | Comparer<T>;
}
export interface EntityStateAdapter<T> {
addOne<S extends EntityState<T>>(entity: T, state: S): S;
addMany<S extends EntityState<T>>(entities: T[], state: S): S;
addAll<S extends EntityState<T>>(entities: T[], state: S): S;
removeOne<S extends EntityState<T>>(key: string, state: S): S;
removeOne<S extends EntityState<T>>(key: number, state: S): S;
removeMany<S extends EntityState<T>>(keys: string[], state: S): S;
removeMany<S extends EntityState<T>>(keys: number[], state: S): S;
removeAll<S extends EntityState<T>>(state: S): S;
updateOne<S extends EntityState<T>>(update: Update<T>, state: S): S;
updateMany<S extends EntityState<T>>(updates: Update<T>[], state: S): S;
}
export type EntitySelectorsBase<T, V> = {
selectEntities: (state: V) => Dictionary<T>;
selectAll: (state: V) => T[];
selectTotal: (state: V) => number;
};
export interface EntitySelectorsStr<T, V> extends EntitySelectorsBase<T, V> {
selectIds: (state: V) => string[];
}
export interface EntitySelectorsNum<T, V> extends EntitySelectorsBase<T, V> {
selectIds: (state: V) => number[];
}
export type EntitySelectors<T, V> =
| EntitySelectorsNum<T, V>
| EntitySelectorsStr<T, V>;
export interface EntityAdapter<T> extends EntityStateAdapter<T> {
getInitialState(): EntityState<T>;
getInitialState<S extends object>(state: S): EntityState<T> & S;
getSelectors(): EntitySelectors<T, EntityState<T>>;
getSelectors<V>(
selectState: (state: V) => EntityState<T>
): EntitySelectors<T, V>;
}