-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathbooks.reducer.ts
77 lines (71 loc) · 2.16 KB
/
books.reducer.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
import { createReducer, on, Action, createSelector } from "@ngrx/store";
import { BookModel, calculateBooksGrossEarnings } from "src/app/shared/models";
import { BooksPageActions, BooksApiActions } from "src/app/books/actions";
const createBook = (books: BookModel[], book: BookModel) => [...books, book];
const updateBook = (books: BookModel[], changes: BookModel) =>
books.map(book => {
return book.id === changes.id ? Object.assign({}, book, changes) : book;
});
const deleteBook = (books: BookModel[], bookId: string) =>
books.filter(book => bookId !== book.id);
export interface State {
collection: BookModel[];
activeBookId: string | null;
}
export const initialState: State = {
collection: [],
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 {
...state,
collection: action.books
};
}),
on(BooksApiActions.bookCreated, (state, action) => {
return {
collection: createBook(state.collection, action.book),
activeBookId: null
};
}),
on(BooksApiActions.bookUpdated, (state, action) => {
return {
collection: updateBook(state.collection, action.book),
activeBookId: null
};
}),
on(BooksApiActions.bookDeleted, (state, action) => {
return {
...state,
collection: deleteBook(state.collection, action.bookId)
};
})
);
export function reducer(state: State | undefined, action: Action) {
return booksReducer(state, action);
}
export const selectAll = (state: State) => state.collection;
export const selectActiveBookId = (state: State) => state.activeBookId;
export const selectActiveBook = createSelector(
selectAll,
selectActiveBookId,
(books, activeBookId) => books.find(book => book.id === activeBookId) || null
);
export const selectEarningsTotals = createSelector(
selectAll,
calculateBooksGrossEarnings
);