-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbooks.reducer.ts
More file actions
72 lines (66 loc) · 1.96 KB
/
books.reducer.ts
File metadata and controls
72 lines (66 loc) · 1.96 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
import { createReducer, on, Action, createSelector } from "@ngrx/store";
import { createEntityAdapter, EntityState } from "@ngrx/entity";
import {
BookModel,
calculateBooksGrossEarnings
} from "src/app/shared/models/book.model";
import { BooksPageActions, BooksApiActions } from "src/app/books/actions";
export interface State extends EntityState<BookModel> {
activeBookId: string | null;
}
export const adapter = createEntityAdapter<BookModel>();
export const initialState: State = adapter.getInitialState({
activeBookId: null
});
export const booksReducer = createReducer(
initialState,
on(BooksPageActions.clearSelectedBook, BooksPageActions.enter, state => {
return {
...state,
activeBookId: null
};
}),
on(BooksPageActions.selectBook, (state, action) => {
return {
...state,
activeBookId: action.bookId
};
}),
on(BooksApiActions.booksLoaded, (state, action) => {
return adapter.addAll(action.books, state);
}),
on(BooksApiActions.bookCreated, (state, action) => {
return adapter.addOne(action.book, {
...state,
activeBookId: null
});
}),
on(BooksApiActions.bookUpdated, (state, action) => {
return adapter.updateOne(
{ id: action.book.id, changes: action.book },
{
...state,
activeBookId: null
}
);
}),
on(BooksApiActions.bookDeleted, (state, action) => {
return adapter.removeOne(action.bookId, state);
})
);
export function reducer(state: State | undefined, action: Action) {
return booksReducer(state, action);
}
export const { selectAll, selectEntities } = adapter.getSelectors();
export const selectActiveBookId = (state: State) => state.activeBookId;
export const selectActiveBook = createSelector(
selectEntities,
selectActiveBookId,
(booksEntities, activeBookId) => {
return activeBookId ? booksEntities[activeBookId]! : null;
}
);
export const selectEarningsTotals = createSelector(
selectAll,
calculateBooksGrossEarnings
);