Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 24 additions & 32 deletions libs/shared-state-books/src/lib/books.reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,15 @@ import { createEntityAdapter, EntityState } from '@ngrx/entity';
import { BookModel, calculateBooksGrossEarnings } from '@book-co/shared-models';
import { BooksPageActions, BooksApiActions } from '@book-co/books-page/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[];
export interface State extends EntityState<BookModel> {
activeBookId: string | null;
}

export const initialState: State = {
collection: [],
export const adapter = createEntityAdapter<BookModel>();

export const initialState: State = adapter.getInitialState({
activeBookId: null,
};
});

export const reducer = createReducer(
initialState,
Expand All @@ -36,38 +28,38 @@ export const reducer = createReducer(
};
}),
on(BooksApiActions.booksLoaded, (state, action) => {
return {
...state,
collection: action.books,
};
return adapter.setAll(action.books, state);
}),
on(BooksApiActions.bookCreated, (state, action) => {
return {
collection: createBook(state.collection, action.book),
return adapter.addOne(action.book, {
...state,
activeBookId: null,
};
});
}),
on(BooksApiActions.bookUpdated, (state, action) => {
return {
collection: updateBook(state.collection, action.book),
activeBookId: null,
};
return adapter.updateOne(
{ id: action.book.id, changes: action.book },
{
...state,
activeBookId: null,
}
);
}),
on(BooksApiActions.bookDeleted, (state, action) => {
return {
...state,
collection: deleteBook(state.collection, action.bookId),
};
return adapter.removeOne(action.bookId, state);
})
);

export const selectAll = (state: State) => state.collection;
export const { selectAll, selectEntities } = adapter.getSelectors();
export const selectActiveBookId = (state: State) => state.activeBookId;
export const selectActiveBook = createSelector(
selectAll,
selectEntities,
selectActiveBookId,
(books, activeBookId) =>
books.find((book) => book.id === activeBookId) || null
(booksEntities, activeBookId) => {
if (activeBookId) return booksEntities[activeBookId] ?? null;

return null;
}
);
export const selectEarningsTotals = createSelector(
selectAll,
Expand Down