-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathbooks.reducer.ts
More file actions
93 lines (81 loc) · 2.37 KB
/
books.reducer.ts
File metadata and controls
93 lines (81 loc) · 2.37 KB
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
import { createEntityAdapter, EntityAdapter, EntityState } from "@ngrx/entity";
import { Book } from "src/app/shared/models/book.model";
import { BooksPageActions, BooksApiActions } from "src/app/books/actions";
import { createSelector } from "@ngrx/store";
export const initialBooks: Book[] = [
{
id: "1",
name: "Fellowship of the Ring",
earnings: 100000000,
description: "The start"
},
{
id: "2",
name: "The Two Towers",
earnings: 200000000,
description: "The middle"
},
{
id: "3",
name: "The Return of The King",
earnings: 400000000,
description: "The end"
}
];
export interface State extends EntityState<Book> {
activeBookId: string | null;
}
export const adapter = createEntityAdapter<Book>();
export const initialState = adapter.getInitialState({
activeBookId: null
});
export function reducer(
state = initialState,
action: BooksPageActions.BooksActions | BooksApiActions.BooksApiActions
): State {
switch (action.type) {
case BooksApiActions.BooksApiActionTypes.BooksLoaded:
return adapter.addAll(action.books, state);
case BooksPageActions.BooksActionTypes.SelectBook:
return {
...state,
activeBookId: action.bookId
};
case BooksPageActions.BooksActionTypes.ClearSelectedBook:
return {
...state,
activeBookId: null
};
case BooksApiActions.BooksApiActionTypes.BookCreated:
return adapter.addOne(action.book, {
...state,
activeBookId: action.book.id
});
case BooksApiActions.BooksApiActionTypes.BookUpdated:
return adapter.updateOne(
{ id: action.book.id, changes: action.book },
{ ...state, activeBookId: action.book.id }
);
case BooksApiActions.BooksApiActionTypes.BookDeleted:
return adapter.removeOne(action.book.id, {
...state,
activeBookId: null
});
default:
return state;
}
}
export const { selectAll, selectEntities } = adapter.getSelectors();
export const selectActiveBookId = (state: State) => state.activeBookId;
export const selectActiveBook = createSelector(
selectEntities,
selectActiveBookId,
(entities, bookId) => (bookId ? entities[bookId] : null)
);
export const selectEarningsTotals = createSelector(
selectAll,
books =>
books.reduce((total, book) => {
return total + parseInt(`${book.earnings}`, 10) || 0;
}, 0)
);