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
/
search.ts
75 lines (61 loc) · 1.86 KB
/
search.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
import {BookActionEnum} from '../actions/book';
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 {
ids: string[];
loading: boolean;
query: string;
}
const initialState: State = {
ids: [],
loading: false,
query: ''
};
export class SearchReducer<T> extends ReducerEnumValue<State, T> {
constructor(action: ActionEnumValue<T>, reduce: ReducerFunction<State, T>) {
super(action, reduce);
}
}
export class SearchReducerEnumType extends ReducerEnum<SearchReducer<any>, State> {
SEARCH = new SearchReducer<string>(BookActionEnum.SEARCH,
(state: State, action: TypedAction<string>): State => {
const query = action.payload;
if (query === '') {
return {
ids: [],
loading: false,
query
};
}
return Object.assign({}, state, {
query,
loading: true
});
});
SEARCH_COMPLETE = new SearchReducer<Book[]>(BookActionEnum.SEARCH_COMPLETE,
(state: State, action: TypedAction<Book[]>): State => {
return {
ids: action.payload.map((book: Book) => book.id),
loading: false,
query: state.query
};
});
constructor() {
super(initialState);
this.initEnum('searchReducers');
}
}
export const SearchReducerEnum = new SearchReducerEnumType();
const reducer: ActionReducer<State> = SearchReducerEnum.reducer();
export function searchReducer(state: State, action: TypedAction<any>): State {
return reducer(state, action);
}
export const getIds = (state: State) => state.ids;
export const getQuery = (state: State) => state.query;
export const getLoading = (state: State) => state.loading;