This repository has been archived by the owner on Apr 3, 2022. It is now read-only.
forked from ngrx/example-app
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcollection.ts
85 lines (70 loc) · 2.42 KB
/
collection.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
import {CollectionActionEnum} from '../actions/collection';
import {Book} from '../models/book';
import {ActionEnumValue, TypedAction} from '../actions/action-enum';
import {
ReducerEnum,
ReducerEnumValue,
ReducerFunction
} from './reducer-enum';
import {ActionReducer} from '@ngrx/store';
export interface State {
loaded: boolean;
loading: boolean;
ids: string[];
}
const initialState: State = {
loaded: false,
loading: false,
ids: []
};
export class CollectionReducer<T> extends ReducerEnumValue<State, T> {
constructor(action: ActionEnumValue<T> | ActionEnumValue<T>[],
reduce: ReducerFunction<State, T>) {
super(action, reduce);
}
}
export class CollectionReducerEnumType extends ReducerEnum<CollectionReducer<any>, State> {
LOAD = new CollectionReducer<void>(CollectionActionEnum.LOAD,
(state: State) => ({...state, loading: true}));
LOAD_SUCCESS = new CollectionReducer<Book[]>(CollectionActionEnum.LOAD_SUCCESS,
(state: State, action: TypedAction<Book[]>) => {
return {
loaded: true,
loading: false,
ids: action.payload.map((book: Book) => book.id)
};
});
ADD_BOOK_SUCCESS = new CollectionReducer<Book>(
[CollectionActionEnum.ADD_BOOK_SUCCESS,
CollectionActionEnum.REMOVE_BOOK_FAIL],
(state: State, action: TypedAction<Book>) => {
const book = action.payload;
if (state.ids.indexOf(book.id) > -1) {
return state;
}
return Object.assign({}, state, {
ids: [ ...state.ids, book.id ]
});
});
REMOVE_BOOK_SUCCESS = new CollectionReducer<Book>(
[CollectionActionEnum.REMOVE_BOOK_SUCCESS,
CollectionActionEnum.ADD_BOOK_FAIL],
(state: State, action: TypedAction<Book>) => {
const book = action.payload;
return Object.assign({}, state, {
ids: state.ids.filter(id => id !== book.id)
});
});
constructor() {
super(initialState);
this.initEnum('collectionReducers');
}
}
export const CollectionReducerEnum = new CollectionReducerEnumType();
const reducer: ActionReducer<State> = CollectionReducerEnum.reducer();
export function collectionReducer(state: State, action: TypedAction<any>): State {
return reducer(state, action);
}
export const getLoaded = (state: State) => state.loaded;
export const getLoading = (state: State) => state.loading;
export const getIds = (state: State) => state.ids;