Instead of Entity[] use EntityState

This commit is contained in:
aditya.chandel
2024-12-28 23:06:54 -07:00
parent da153d6c04
commit a5e321319a
17 changed files with 398 additions and 251 deletions
@@ -13,6 +13,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.io.IOException; import java.io.IOException;
import java.time.Duration;
import java.util.List; import java.util.List;
@RequestMapping("/v1/book") @RequestMapping("/v1/book")
@@ -28,8 +29,9 @@ public class BookController {
} }
@GetMapping @GetMapping
public ResponseEntity<List<BookDTO>> getBooks() { public ResponseEntity<List<BookDTO>> getBooks() throws InterruptedException {
return ResponseEntity.ok( booksService.getBooks()); Thread.sleep(Duration.ofSeconds(3));
return ResponseEntity.ok(booksService.getBooks());
} }
@GetMapping("/search") @GetMapping("/search")
@@ -22,7 +22,7 @@
</div> </div>
<div class="virtual-scroller-container"> <div class="virtual-scroller-container">
<div class="book-card-container" *ngIf="books$ | async as books"> <div class="book-card-container" *ngIf="(bookState$ | async)?.books as books">
<virtual-scroller *ngIf="books.length > 0" class="virtual-scroller" #scroll [items]="books"> <virtual-scroller *ngIf="books.length > 0" class="virtual-scroller" #scroll [items]="books">
<div class="grid" #container> <div class="grid" #container>
<div class="virtual-scroller-item" *ngFor="let book of scroll.viewPortItems"> <div class="virtual-scroller-item" *ngFor="let book of scroll.viewPortItems">
@@ -5,7 +5,6 @@ import {LibraryService} from '../../service/library.service';
import {BookService} from '../../service/book.service'; import {BookService} from '../../service/book.service';
import {map, switchMap} from 'rxjs/operators'; import {map, switchMap} from 'rxjs/operators';
import {BehaviorSubject, Observable, of} from 'rxjs'; import {BehaviorSubject, Observable, of} from 'rxjs';
import {Book} from '../../model/book.model';
import {ShelfService} from '../../service/shelf.service'; import {ShelfService} from '../../service/shelf.service';
import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component'; import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog'; import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
@@ -14,6 +13,7 @@ import {Shelf} from '../../model/shelf.model';
import {SortService} from '../../service/sort.service'; import {SortService} from '../../service/sort.service';
import {SortOptionsHelper} from '../../service/sort-options.helper'; import {SortOptionsHelper} from '../../service/sort-options.helper';
import {SortOption} from '../../model/sort.model'; import {SortOption} from '../../model/sort.model';
import {BookState} from '../../model/state/book-state.model';
@Component({ @Component({
selector: 'app-books-browser', selector: 'app-books-browser',
@@ -22,7 +22,7 @@ import {SortOption} from '../../model/sort.model';
styleUrls: ['./books-browser.component.scss'] styleUrls: ['./books-browser.component.scss']
}) })
export class BooksBrowserComponent implements OnInit { export class BooksBrowserComponent implements OnInit {
books$: Observable<Book[]> | undefined; bookState$: Observable<BookState> | undefined;
entity$: Observable<Library | Shelf | null> | undefined; entity$: Observable<Library | Shelf | null> | undefined;
entityType$: Observable<string | null> | undefined; entityType$: Observable<string | null> | undefined;
bookTitle$ = new BehaviorSubject<string>(''); bookTitle$ = new BehaviorSubject<string>('');
@@ -38,7 +38,6 @@ export class BooksBrowserComponent implements OnInit {
isDrawerVisible: boolean = false; isDrawerVisible: boolean = false;
ref: DynamicDialogRef | undefined; ref: DynamicDialogRef | undefined;
constructor( constructor(
private activatedRoute: ActivatedRoute, private activatedRoute: ActivatedRoute,
private router: Router, private router: Router,
@@ -56,7 +55,7 @@ export class BooksBrowserComponent implements OnInit {
this.sortOptions = SortOptionsHelper.generateSortOptions(); this.sortOptions = SortOptionsHelper.generateSortOptions();
const routeParam$ = this.getRouteParams(); const routeParam$ = this.getRouteParams();
this.books$ = routeParam$.pipe( this.bookState$ = routeParam$.pipe(
switchMap(({libraryId, shelfId}) => this.fetchBooks(libraryId, shelfId)), switchMap(({libraryId, shelfId}) => this.fetchBooks(libraryId, shelfId)),
); );
@@ -91,13 +90,17 @@ export class BooksBrowserComponent implements OnInit {
); );
} }
private fetchBooks(libraryId: number, shelfId: number): Observable<Book[]> { private fetchBooks(libraryId: number, shelfId: number): Observable<BookState> {
if (libraryId) { if (libraryId) {
return this.fetchBooksByLibrary(libraryId); return this.fetchBooksByLibrary(libraryId);
} else if (shelfId) { } else if (shelfId) {
return this.fetchBooksByShelf(shelfId); return this.fetchBooksByShelf(shelfId);
} }
return of([]); return of({
books: [],
loaded: false,
error: null
});
} }
private fetchEntity(libraryId: number, shelfId: number): Observable<Library | Shelf | null> { private fetchEntity(libraryId: number, shelfId: number): Observable<Library | Shelf | null> {
@@ -113,45 +116,89 @@ export class BooksBrowserComponent implements OnInit {
return of(null); return of(null);
} }
private fetchBooksByLibrary(libraryId: number): Observable<Book[]> { private fetchBooksByLibrary(libraryId: number): Observable<BookState> {
return this.bookService.books$.pipe( return this.bookService.bookState$.pipe(
map(books => books.filter(book => book.libraryId === libraryId)), map(bookState => {
map(books => this.sortService.applySort(books, this.selectedSort)), if (bookState.books) {
switchMap(books => this.bookTitle$.pipe( const filteredBooks = bookState.books.filter(book => book.libraryId === libraryId);
map(title => { return this.sortService.applySort(filteredBooks, this.selectedSort);
if (title && title.trim() !== '') { } else {
return books.filter(book => book.metadata?.title?.toLowerCase().includes(title.toLowerCase())); return [];
} }
return books; }),
}) switchMap(books =>
)) this.bookTitle$.pipe(
map(title => {
if (title && title.trim() !== '') {
return books.filter(book => book.metadata?.title?.toLowerCase().includes(title.toLowerCase()));
}
return books;
})
)
),
map(filteredBooks => {
return {
books: filteredBooks,
loaded: true,
error: null
} as BookState;
})
); );
} }
private fetchBooksByShelf(shelfId: number): Observable<Book[]> { private fetchBooksByShelf(shelfId: number): Observable<BookState> {
return this.bookService.books$.pipe( return this.bookService.bookState$.pipe(
map(books => books.filter(book => book.shelves?.some(shelf => shelf.id === shelfId))), map(bookState => {
map(books => this.sortService.applySort(books, this.selectedSort)), if (bookState.books) {
switchMap(books => this.bookTitle$.pipe( const filteredBooks = bookState.books.filter(book =>
map(title => { book.shelves?.some(shelf => shelf.id === shelfId)
if (title && title.trim() !== '') { );
return books.filter(book => book.metadata?.title?.toLowerCase().includes(title.toLowerCase())); return this.sortService.applySort(filteredBooks, this.selectedSort);
} } else {
return books; return [];
}) }
)) }),
switchMap(books =>
this.bookTitle$.pipe(
map(title => {
if (title && title.trim() !== '') {
return books.filter(book =>
book.metadata?.title?.toLowerCase().includes(title.toLowerCase())
);
}
return books;
})
)
),
map(filteredBooks => {
return {
books: filteredBooks,
loaded: true,
error: null
} as BookState;
})
); );
} }
private fetchLibrary(libraryId: number): Observable<Library | null> { private fetchLibrary(libraryId: number): Observable<Library | null> {
return this.libraryService.libraries$.pipe( return this.libraryService.libraryState$.pipe(
map(libraries => libraries.find(lib => lib.id === libraryId) || null) map(libraryState => {
if (libraryState.libraries) {
return libraryState.libraries.find(lib => lib.id === libraryId) || null;
}
return null;
})
); );
} }
private fetchShelf(shelfId: number): Observable<Shelf | null> { private fetchShelf(shelfId: number): Observable<Shelf | null> {
return this.shelfService.shelves$.pipe( return this.shelfService.shelfState$.pipe(
map(shelves => shelves.find(shelf => shelf.id === shelfId) || null) map(shelfState => {
if (shelfState.shelves) {
return shelfState.shelves.find(shelf => shelf.id === shelfId) || null;
}
return null;
})
); );
} }
@@ -186,7 +233,7 @@ export class BooksBrowserComponent implements OnInit {
updateSortOption(sortOption: SortOption): void { updateSortOption(sortOption: SortOption): void {
this.selectedSort = sortOption; this.selectedSort = sortOption;
const routeParam$ = this.getRouteParams(); const routeParam$ = this.getRouteParams();
this.books$ = routeParam$.pipe( this.bookState$ = routeParam$.pipe(
switchMap(({libraryId, shelfId}) => this.fetchBooks(libraryId, shelfId)) switchMap(({libraryId, shelfId}) => this.fetchBooks(libraryId, shelfId))
); );
if (this.entityType === 'Library') { if (this.entityType === 'Library') {
@@ -255,7 +302,7 @@ export class BooksBrowserComponent implements OnInit {
icon: 'pi pi-exclamation-triangle', icon: 'pi pi-exclamation-triangle',
acceptIcon: 'none', acceptIcon: 'none',
rejectIcon: 'none', rejectIcon: 'none',
rejectButtonStyleClass: 'p-button-text', acceptButtonStyleClass: 'p-button-text',
accept: () => { accept: () => {
this.libraryService.deleteLibrary(this.entity?.id!).subscribe({ this.libraryService.deleteLibrary(this.entity?.id!).subscribe({
complete: () => { complete: () => {
@@ -285,7 +332,7 @@ export class BooksBrowserComponent implements OnInit {
icon: 'pi pi-exclamation-triangle', icon: 'pi pi-exclamation-triangle',
acceptIcon: 'none', acceptIcon: 'none',
rejectIcon: 'none', rejectIcon: 'none',
rejectButtonStyleClass: 'p-button-text', acceptButtonStyleClass: 'p-button-text',
accept: () => { accept: () => {
this.libraryService.refreshLibrary(this.entity?.id!).subscribe({ this.libraryService.refreshLibrary(this.entity?.id!).subscribe({
complete: () => { complete: () => {
@@ -328,7 +375,7 @@ export class BooksBrowserComponent implements OnInit {
icon: 'pi pi-exclamation-triangle', icon: 'pi pi-exclamation-triangle',
acceptIcon: 'none', acceptIcon: 'none',
rejectIcon: 'none', rejectIcon: 'none',
rejectButtonStyleClass: 'p-button-text', acceptButtonStyleClass: 'p-button-text',
accept: () => { accept: () => {
this.shelfService.deleteShelf(this.entity?.id!).subscribe({ this.shelfService.deleteShelf(this.entity?.id!).subscribe({
complete: () => { complete: () => {
@@ -352,5 +399,4 @@ export class BooksBrowserComponent implements OnInit {
}, },
]; ];
} }
} }
@@ -1,6 +1,6 @@
<div class="dashboard-scroller-container"> <div class="dashboard-scroller-container">
<h2 class="dashboard-scroller-title">{{ title }}</h2> <h2 class="dashboard-scroller-title">{{ title }}</h2>
<div *ngIf="(books$ | async)?.length === 0"> <div *ngIf="(bookState$ | async)?.books?.length === 0">
<h4>No books available.</h4> <h4>No books available.</h4>
</div> </div>
<div class="infinite-scroller" <div class="infinite-scroller"
@@ -9,7 +9,7 @@
[infiniteScrollThrottle]="50" [infiniteScrollThrottle]="50"
#scrollContainer #scrollContainer
[horizontal]="true"> [horizontal]="true">
<div class="infinite-scroller-a-book" *ngFor="let book of books$ | async"> <div class="infinite-scroller-a-book" *ngFor="let book of (bookState$ | async)?.books">
<app-book-card [book]="book" [isCheckboxEnabled]="false"></app-book-card> <app-book-card [book]="book" [isCheckboxEnabled]="false"></app-book-card>
</div> </div>
</div> </div>
@@ -1,11 +1,11 @@
import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core'; import { Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
import {Book} from '../../model/book.model'; import { Observable } from 'rxjs';
import {InfiniteScrollDirective} from 'ngx-infinite-scroll'; import { map } from 'rxjs/operators';
import {AsyncPipe, NgForOf, NgIf} from '@angular/common'; import { BookService } from '../../service/book.service';
import {BookCardComponent} from '../book-card/book-card.component'; import { BookState } from '../../model/state/book-state.model';
import {Observable} from 'rxjs'; import { BookCardComponent } from '../book-card/book-card.component';
import {BookService} from '../../service/book.service'; import { InfiniteScrollDirective } from 'ngx-infinite-scroll';
import {map} from 'rxjs/operators'; import { AsyncPipe, NgForOf, NgIf } from '@angular/common';
@Component({ @Component({
selector: 'app-dashboard-scroller', selector: 'app-dashboard-scroller',
@@ -25,31 +25,33 @@ export class DashboardScrollerComponent implements OnInit {
@Input() title: string = 'Last Read Books'; @Input() title: string = 'Last Read Books';
@ViewChild('scrollContainer') scrollContainer!: ElementRef; @ViewChild('scrollContainer') scrollContainer!: ElementRef;
books$: Observable<Book[]> | undefined; bookState$: Observable<BookState> | undefined;
constructor(private bookService: BookService) { constructor(private bookService: BookService) {}
}
ngOnInit(): void { ngOnInit(): void {
if (this.bookListType === 'lastRead') { if (this.bookListType === 'lastRead') {
this.books$ = this.bookService.books$.pipe(( this.bookState$ = this.bookService.bookState$.pipe(
map(books => map((state: BookState) => ({
books ...state,
.filter(book => book.lastReadTime) books: (state.books || [])
.sort((a, b) => new Date(b.lastReadTime!).getTime() - new Date(a.lastReadTime!).getTime()) .filter(book => book.lastReadTime)
.slice(0, 25) .sort((a, b) => new Date(b.lastReadTime!).getTime() - new Date(a.lastReadTime!).getTime())
) .slice(0, 25)
)) }))
);
} }
if (this.bookListType === 'latestAdded') { if (this.bookListType === 'latestAdded') {
this.books$ = this.bookService.books$.pipe(( this.bookState$ = this.bookService.bookState$.pipe(
map(books => map((state: BookState) => ({
books ...state,
books: (state.books || [])
.filter(book => book.addedOn) .filter(book => book.addedOn)
.sort((a, b) => new Date(b.addedOn!).getTime() - new Date(a.addedOn!).getTime()) .sort((a, b) => new Date(b.addedOn!).getTime() - new Date(a.addedOn!).getTime())
.slice(0, 25) .slice(0, 25)
) }))
)) );
} }
} }
} }
@@ -1,12 +1,12 @@
import {Component} from '@angular/core'; import { Component } from '@angular/core';
import {Button} from 'primeng/button'; import { Button } from 'primeng/button';
import {AsyncPipe, NgIf} from '@angular/common'; import { AsyncPipe, NgIf } from '@angular/common';
import {LibraryCreatorComponent} from '../library-creator/library-creator.component'; import { LibraryCreatorComponent } from '../library-creator/library-creator.component';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog'; import { DialogService, DynamicDialogRef } from 'primeng/dynamicdialog';
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component'; import { DashboardScrollerComponent } from '../dashboard-scroller/dashboard-scroller.component';
import {LibraryService} from '../../service/library.service'; import { LibraryService } from '../../service/library.service';
import {Observable} from 'rxjs'; import { Observable } from 'rxjs';
import {map} from 'rxjs/operators'; import { map } from 'rxjs/operators';
@Component({ @Component({
selector: 'app-home-page', selector: 'app-home-page',
@@ -25,8 +25,8 @@ export class DashboardComponent {
ref: DynamicDialogRef | undefined; ref: DynamicDialogRef | undefined;
constructor(private libraryService: LibraryService, public dialogService: DialogService) { constructor(private libraryService: LibraryService, public dialogService: DialogService) {
this.isLibrariesEmpty$ = this.libraryService.libraries$.pipe( this.isLibrariesEmpty$ = this.libraryService.libraryState$.pipe(
map(libraries => libraries.length === 0) map(state => !state.libraries || state.libraries.length === 0)
); );
} }
@@ -36,7 +36,7 @@ export class DashboardComponent {
modal: true, modal: true,
width: '50%', width: '50%',
height: '50%', height: '50%',
style: {bottom: '15%'} style: { bottom: '15%' }
}); });
} }
} }
@@ -2,7 +2,7 @@
<div class="flex"> <div class="flex">
<p-dropdown <p-dropdown
[options]="(libraries$ | async) || []" [options]="(libraryState$ | async)?.libraries || []"
optionLabel="name" optionLabel="name"
placeholder="Select Library" placeholder="Select Library"
[(ngModel)]="selectedLibrary"> [(ngModel)]="selectedLibrary">
@@ -9,6 +9,7 @@ import {ToastService} from '../../service/toast.service';
import {DynamicDialogRef} from 'primeng/dynamicdialog'; import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {LibraryService} from '../../service/library.service'; import {LibraryService} from '../../service/library.service';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {LibraryState} from '../../model/state/library-state.model';
@Component({ @Component({
selector: 'app-file-upload-v2', selector: 'app-file-upload-v2',
@@ -23,7 +24,7 @@ import {Observable} from 'rxjs';
], ],
}) })
export class FileUploadComponent { export class FileUploadComponent {
libraries$: Observable<Library[]>; libraryState$: Observable<LibraryState>;
selectedLibrary: Library | null = null; selectedLibrary: Library | null = null;
selectedPath: string = ''; selectedPath: string = '';
selectedFileName: string = ''; selectedFileName: string = '';
@@ -35,7 +36,7 @@ export class FileUploadComponent {
private fileUploadService: FileUploadService, private fileUploadService: FileUploadService,
private toastService: ToastService, private toastService: ToastService,
private dynamicDialogRef: DynamicDialogRef) { private dynamicDialogRef: DynamicDialogRef) {
this.libraries$ = this.libraryService.libraries$; this.libraryState$ = this.libraryService.libraryState$;
} }
triggerFileInput(fileInput: HTMLInputElement): void { triggerFileInput(fileInput: HTMLInputElement): void {
@@ -1,11 +1,11 @@
import {Component, computed, OnInit} from '@angular/core'; import { Component, OnInit } from '@angular/core';
import {AppMenuitemComponent} from './app.menuitem.component'; import { AppMenuitemComponent } from './app.menuitem.component';
import {AsyncPipe, NgForOf, NgIf} from '@angular/common'; import { AsyncPipe, NgForOf, NgIf } from '@angular/common';
import {MenuModule} from 'primeng/menu'; import { MenuModule } from 'primeng/menu';
import {LibraryService} from '../../service/library.service'; import { LibraryService } from '../../service/library.service';
import {async, Observable} from 'rxjs'; import { Observable } from 'rxjs';
import {map} from 'rxjs/operators'; import { map } from 'rxjs/operators';
import {ShelfService} from '../../service/shelf.service'; import { ShelfService } from '../../service/shelf.service';
@Component({ @Component({
selector: 'app-menu', selector: 'app-menu',
@@ -17,36 +17,35 @@ export class AppMenuComponent implements OnInit {
libraryMenu$: Observable<any> | undefined; libraryMenu$: Observable<any> | undefined;
shelfMenu$: Observable<any> | undefined; shelfMenu$: Observable<any> | undefined;
constructor(private libraryService: LibraryService, private shelfService: ShelfService) { constructor(private libraryService: LibraryService, private shelfService: ShelfService) {}
}
ngOnInit() { ngOnInit(): void {
this.libraryMenu$ = this.libraryService.libraries$.pipe( this.libraryMenu$ = this.libraryService.libraryState$.pipe(
map((libraries) => [ map((state) => [
{ {
label: 'Library', label: 'Library',
separator: false, separator: false,
items: libraries.map((library) => ({ items: state.libraries?.map((library) => ({
label: library.name, label: library.name,
icon: 'pi pi-' + library.icon, icon: 'pi pi-' + library.icon,
routerLink: [`/library/${library.id}/books`], routerLink: [`/library/${library.id}/books`],
bookCount$: this.libraryService.getBookCount(library.id ?? 0), bookCount$: this.libraryService.getBookCount(library.id ?? 0),
})), })) || [],
}, },
]) ])
); );
this.shelfMenu$ = this.shelfService.shelves$.pipe( this.shelfMenu$ = this.shelfService.shelfState$.pipe(
map((shelves) => [ map((state) => [
{ {
label: 'Shelves', label: 'Shelves',
separator: false, separator: false,
items: shelves.map((shelf) => ({ items: state.shelves?.map((shelf) => ({
label: shelf.name, label: shelf.name,
icon: 'pi pi-' + shelf.icon, icon: 'pi pi-' + shelf.icon,
routerLink: [`/shelf/${shelf.id}/books`], routerLink: [`/shelf/${shelf.id}/books`],
bookCount$: this.shelfService.getBookCount(shelf.id ?? 0), bookCount$: this.shelfService.getBookCount(shelf.id ?? 0),
})), })) || [],
}, },
]) ])
); );
@@ -54,15 +53,14 @@ export class AppMenuComponent implements OnInit {
this.populateHome(); this.populateHome();
} }
populateHome() { populateHome(): void {
this.home = [ this.home = [
{ {
label: 'Home', label: 'Home',
items: [ items: [
{label: 'Dashboard', icon: 'pi pi-fw pi-home', routerLink: ['/']} { label: 'Dashboard', icon: 'pi pi-fw pi-home', routerLink: ['/'] },
], ],
}, },
]; ];
} }
} }
@@ -1,12 +1,11 @@
<div class="dialog-container"> <div class="dialog-container">
<div class="checkbox-list"> <div class="checkbox-list">
<div *ngFor="let shelf of shelves$ | async" class="flex items-center"> <div *ngFor="let shelf of (shelfState$ | async)?.shelves" class="flex items-center">
<p-checkbox [inputId]="shelf.name" name="group" [value]="shelf" [(ngModel)]="selectedShelves"/> <p-checkbox [inputId]="shelf.name" name="group" [value]="shelf" [(ngModel)]="selectedShelves"></p-checkbox>
<label [for]="shelf.id" class="ml-2">{{ shelf.name }}</label> <label [for]="shelf.id" class="ml-2">{{ shelf.name }}</label>
</div> </div>
</div> </div>
<!-- Divider and Bottom Section -->
<div class="bottom-section"> <div class="bottom-section">
<p-divider></p-divider> <p-divider></p-divider>
<div class="bottom-container"> <div class="bottom-container">
@@ -17,12 +16,13 @@
</div> </div>
</div> </div>
</div> </div>
<app-icon-picker (iconSelected)="onIconSelected($event)"></app-icon-picker> <app-icon-picker (iconSelected)="onIconSelected($event)"></app-icon-picker>
<p-dialog [(visible)]="displayShelfDialog" header="Create Shelf" [modal]="true" [draggable]="false" [closable]="true" (onHide)="closeShelfDialog()" [style]="{ width: '400px', height: 'auto' }"> <p-dialog [(visible)]="displayShelfDialog" header="Create Shelf" [modal]="true" [draggable]="false" [closable]="true" (onHide)="closeShelfDialog()" [style]="{ width: '400px', height: 'auto' }">
<div class="p-fluid"> <div class="p-fluid">
<div class="field"> <div class="field">
<label for="shelfName">Shelf Name</label> <label for="shelfName">Shelf Name</label>
<input id="shelfName" type="text" pInputText [(ngModel)]="shelfName"/> <input id="shelfName" type="text" pInputText [(ngModel)]="shelfName" />
</div> </div>
<div class="field"> <div class="field">
<label>Shelf Icon</label> <label>Shelf Icon</label>
@@ -31,7 +31,7 @@
</div> </div>
<div *ngIf="selectedIcon" class="mt-2 flex align-items-center"> <div *ngIf="selectedIcon" class="mt-2 flex align-items-center">
<i [class]="selectedIcon" class="mr-2"></i> <i [class]="selectedIcon" class="mr-2"></i>
<p-button label="Remove" icon="pi pi-times" [text]="true" [outlined]="true" severity="warning" (onClick)="clearSelectedIcon()"></p-button> <p-button label="Remove" icon="pi pi-times" text="true" outlined="true" severity="warning" (onClick)="clearSelectedIcon()"></p-button>
</div> </div>
</div> </div>
</div> </div>
@@ -1,13 +1,14 @@
import {Component, OnInit, ViewChild} from '@angular/core'; import { Component, OnInit, ViewChild } from '@angular/core';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog';
import {Book} from '../../model/book.model'; import { Book } from '../../model/book.model';
import {MessageService} from 'primeng/api'; import { MessageService } from 'primeng/api';
import {ShelfService} from '../../service/shelf.service'; import { ShelfService } from '../../service/shelf.service';
import {Observable} from 'rxjs'; import { Observable } from 'rxjs';
import {BookService} from '../../service/book.service'; import { BookService } from '../../service/book.service';
import {map, tap} from 'rxjs/operators'; import { map, tap } from 'rxjs/operators';
import {Shelf} from '../../model/shelf.model'; import { Shelf } from '../../model/shelf.model';
import {IconPickerComponent} from '../icon-picker/icon-picker.component'; import { IconPickerComponent } from '../icon-picker/icon-picker.component';
import { ShelfState } from '../../model/state/shelf-state.model';
@Component({ @Component({
selector: 'app-shelf-assigner', selector: 'app-shelf-assigner',
@@ -16,7 +17,7 @@ import {IconPickerComponent} from '../icon-picker/icon-picker.component';
styleUrls: ['./shelf-assigner.component.scss'] styleUrls: ['./shelf-assigner.component.scss']
}) })
export class ShelfAssignerComponent implements OnInit { export class ShelfAssignerComponent implements OnInit {
shelves$: Observable<Shelf[]>; shelfState$: Observable<ShelfState>;
book: Book; book: Book;
selectedShelves: Shelf[] = []; selectedShelves: Shelf[] = [];
displayShelfDialog: boolean = false; displayShelfDialog: boolean = false;
@@ -24,6 +25,7 @@ export class ShelfAssignerComponent implements OnInit {
bookIds: Set<number> = new Set(); bookIds: Set<number> = new Set();
isMultiBooks: boolean = false; isMultiBooks: boolean = false;
selectedIcon: string | null = null; selectedIcon: string | null = null;
@ViewChild(IconPickerComponent) iconPicker: IconPickerComponent | undefined; @ViewChild(IconPickerComponent) iconPicker: IconPickerComponent | undefined;
constructor( constructor(
@@ -33,33 +35,37 @@ export class ShelfAssignerComponent implements OnInit {
private messageService: MessageService, private messageService: MessageService,
private bookService: BookService private bookService: BookService
) { ) {
this.shelves$ = this.shelfService.shelves$; this.shelfState$ = this.shelfService.shelfState$;
this.book = this.dynamicDialogConfig.data.book; this.book = this.dynamicDialogConfig.data.book;
this.bookIds = this.dynamicDialogConfig.data.bookIds; this.bookIds = this.dynamicDialogConfig.data.bookIds;
this.isMultiBooks = this.dynamicDialogConfig.data.isMultiBooks; this.isMultiBooks = this.dynamicDialogConfig.data.isMultiBooks;
} }
ngOnInit(): void { ngOnInit(): void {
if (!this.isMultiBooks) { if (!this.isMultiBooks && this.book.shelves) {
this.shelves$.pipe( this.shelfState$.pipe(
map(shelves => shelves.filter(shelf => this.book.shelves?.some(bShelf => bShelf.id === shelf.id))), map(state => state.shelves || []),
tap(selectedShelves => this.selectedShelves = selectedShelves) tap(shelves => {
this.selectedShelves = shelves.filter(shelf =>
this.book.shelves?.some(bShelf => bShelf.id === shelf.id)
);
})
).subscribe(); ).subscribe();
} }
} }
saveNewShelf(): void { saveNewShelf(): void {
const newShelf = { const newShelf: Partial<Shelf> = {
name: this.shelfName, name: this.shelfName,
icon: this.selectedIcon ? this.selectedIcon.replace('pi pi-', '') : 'heart' icon: this.selectedIcon ? this.selectedIcon.replace('pi pi-', '') : 'heart'
}; };
this.shelfService.createShelf(newShelf).subscribe( this.shelfService.createShelf(newShelf as Shelf).subscribe(
() => { () => {
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Shelf created: ' + this.shelfName}); this.messageService.add({ severity: 'info', summary: 'Success', detail: `Shelf created: ${this.shelfName}` });
this.displayShelfDialog = false; this.displayShelfDialog = false;
}, },
error => { error => {
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to create shelf'}); this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Failed to create shelf' });
console.error('Error creating shelf:', error); console.error('Error creating shelf:', error);
} }
); );
@@ -75,11 +81,11 @@ export class ShelfAssignerComponent implements OnInit {
private updateBookShelves(bookIds: Set<number>, idsToAssign: Set<number | undefined>, idsToUnassign: Set<number>): void { private updateBookShelves(bookIds: Set<number>, idsToAssign: Set<number | undefined>, idsToUnassign: Set<number>): void {
this.bookService.updateBookShelves(bookIds, idsToAssign, idsToUnassign).subscribe( this.bookService.updateBookShelves(bookIds, idsToAssign, idsToUnassign).subscribe(
() => { () => {
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Book shelves updated'}); this.messageService.add({ severity: 'info', summary: 'Success', detail: 'Book shelves updated' });
this.dynamicDialogRef.close(); this.dynamicDialogRef.close();
}, },
error => { error => {
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update book shelves'}); this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Failed to update book shelves' });
this.dynamicDialogRef.close(); this.dynamicDialogRef.close();
} }
); );
@@ -88,7 +94,7 @@ export class ShelfAssignerComponent implements OnInit {
private getIdsToUnAssign(book: Book, idsToAssign: Set<number | undefined>): Set<number> { private getIdsToUnAssign(book: Book, idsToAssign: Set<number | undefined>): Set<number> {
const idsToUnassign = new Set<number>(); const idsToUnassign = new Set<number>();
book.shelves?.forEach(shelf => { book.shelves?.forEach(shelf => {
if (!idsToAssign.has(shelf.id!)) { if (!idsToAssign.has(shelf.id)) {
idsToUnassign.add(shelf.id!); idsToUnassign.add(shelf.id!);
} }
}); });
@@ -120,5 +126,4 @@ export class ShelfAssignerComponent implements OnInit {
onIconSelected(icon: string) { onIconSelected(icon: string) {
this.selectedIcon = icon; this.selectedIcon = icon;
} }
} }
@@ -0,0 +1,7 @@
import {Book} from '../book.model';
export interface BookState {
books: Book[] | null;
loaded: boolean;
error: string | null;
}
@@ -0,0 +1,7 @@
import {Library} from '../library.model';
export interface LibraryState {
libraries: Library[] | null;
loaded: boolean;
error: string | null;
}
@@ -0,0 +1,7 @@
import {Shelf} from '../shelf.model';
export interface ShelfState {
shelves: Shelf[] | null;
loaded: boolean;
error: string | null;
}
@@ -1,26 +1,43 @@
import {Injectable} from '@angular/core'; import { Injectable } from '@angular/core';
import {BehaviorSubject, Observable, of} from 'rxjs'; import { BehaviorSubject, Observable, of } from 'rxjs';
import {HttpClient} from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import {catchError, map, switchMap} from 'rxjs/operators'; import { catchError, map, switchMap } from 'rxjs/operators';
import {Book, BookMetadata, BookSetting} from '../model/book.model'; import { Book, BookMetadata, BookSetting } from '../model/book.model';
import { BookState } from '../model/state/book-state.model';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class BookService { export class BookService {
private readonly url = 'http://localhost:8080/v1/book'; private readonly url = 'http://localhost:8080/v1/book';
private books = new BehaviorSubject<Book[]>([]);
books$ = this.books.asObservable(); private bookStateSubject = new BehaviorSubject<BookState>({
books: null,
loaded: false,
error: null,
});
bookState$ = this.bookStateSubject.asObservable();
constructor(private http: HttpClient) { constructor(private http: HttpClient) {
this.loadBooks();
}
private loadBooks(): void {
this.http.get<Book[]>(this.url).pipe( this.http.get<Book[]>(this.url).pipe(
catchError(error => { catchError(error => {
console.error('Error loading books:', error); this.bookStateSubject.next({
return of([]); books: null,
loaded: true,
error: error.message,
});
return of(null);
}) })
).subscribe((libraries) => { ).subscribe(books => {
this.books.next(libraries); this.bookStateSubject.next({
books: books || [],
loaded: true,
error: null,
});
}); });
} }
@@ -31,42 +48,46 @@ export class BookService {
shelvesToUnassign: Array.from(shelvesToUnassign), shelvesToUnassign: Array.from(shelvesToUnassign),
}; };
return this.http.post<Book[]>(`${this.url}/assign-shelves`, requestPayload).pipe( return this.http.post<Book[]>(`${this.url}/assign-shelves`, requestPayload).pipe(
map((updatedBooks) => { map(updatedBooks => {
const currentBooks = this.books.value; const currentState = this.bookStateSubject.value;
const currentBooks = currentState.books || [];
updatedBooks.forEach(updatedBook => { updatedBooks.forEach(updatedBook => {
const bookIndex = currentBooks.findIndex(b => b.id === updatedBook.id); const index = currentBooks.findIndex(b => b.id === updatedBook.id);
if (bookIndex !== -1) { if (index !== -1) {
currentBooks[bookIndex] = updatedBook; currentBooks[index] = updatedBook;
} }
}); });
this.books.next([...currentBooks]); this.bookStateSubject.next({ ...currentState, books: [...currentBooks] });
return updatedBooks; return updatedBooks;
}), }),
catchError(error => { catchError(error => {
console.error('Error assigning shelves to books:', error); const currentState = this.bookStateSubject.value;
this.bookStateSubject.next({ ...currentState, error: error.message });
throw error; throw error;
}) })
); );
} }
removeBooksByLibraryId(libraryId: number): void { removeBooksByLibraryId(libraryId: number): void {
const filteredBooks = this.books.value.filter(book => book.libraryId !== libraryId); const currentState = this.bookStateSubject.value;
this.books.next(filteredBooks); const currentBooks = currentState.books || [];
const filteredBooks = currentBooks.filter(book => book.libraryId !== libraryId);
this.bookStateSubject.next({ ...currentState, books: filteredBooks });
} }
removeBooksFromShelf(shelfId: number): void { removeBooksFromShelf(shelfId: number): void {
const books = this.books.value.filter(book => { const currentState = this.bookStateSubject.value;
if (book.shelves) { const currentBooks = currentState.books || [];
book.shelves = book.shelves.filter(shelf => shelf.id !== shelfId); const updatedBooks = currentBooks.map(book => ({
} ...book,
return book; shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
}) }));
this.books.next(books); this.bookStateSubject.next({ ...currentState, books: updatedBooks });
} }
getBookById(bookId: number): Observable<Book | undefined> { getBookById(bookId: number): Observable<Book | undefined> {
return this.books$.pipe( return this.bookState$.pipe(
map(books => books.find(book => book.id === bookId)) map(state => state.books?.find(book => book.id === bookId))
); );
} }
@@ -75,19 +96,17 @@ export class BookService {
} }
updateViewerSetting(viewerSetting: any, bookId: number): Observable<void> { updateViewerSetting(viewerSetting: any, bookId: number): Observable<void> {
const url = `${this.url}/${bookId}/viewer-setting`; return this.http.put<void>(`${this.url}/${bookId}/viewer-setting`, viewerSetting);
return this.http.put<void>(url, viewerSetting);
} }
updateLastReadTime(bookId: number): Observable<Book> { updateLastReadTime(bookId: number): Observable<Book> {
return this.http.put<Book>(`${this.url}/${bookId}/update-last-read`, {}).pipe( return this.http.put<Book>(`${this.url}/${bookId}/update-last-read`, {}).pipe(
switchMap(updatedBook => { switchMap(updatedBook => {
console.log(updatedBook); const currentState = this.bookStateSubject.value;
const currentBooks = this.books.getValue(); const updatedBooks = (currentState.books || []).map(book =>
const updatedBooks = currentBooks.map(book => book.id === updatedBook.id ? { ...book, lastReadTime: updatedBook.lastReadTime } : book
book.id === updatedBook.id ? {...book, lastReadTime: updatedBook.lastReadTime} : book
); );
this.books.next(updatedBooks); this.bookStateSubject.next({ ...currentState, books: updatedBooks });
return [updatedBook]; return [updatedBook];
}) })
); );
@@ -97,9 +116,7 @@ export class BookService {
const url = `/pdf-viewer/book/${book.id}`; const url = `/pdf-viewer/book/${book.id}`;
window.open(url, '_blank'); window.open(url, '_blank');
this.updateLastReadTime(book.id).subscribe({ this.updateLastReadTime(book.id).subscribe({
complete: () => { error: err => console.error('Failed to update last read time', err),
},
error: (err) => console.error('Failed to update last read time', err),
}); });
} }
@@ -107,10 +124,13 @@ export class BookService {
if (query.length < 2) { if (query.length < 2) {
return of([]); return of([]);
} }
const filteredBooks = this.books.value.filter(book => return this.bookState$.pipe(
book.metadata?.title?.toLowerCase().includes(query.toLowerCase()) || false map(state =>
(state.books || []).filter(book =>
book.metadata?.title?.toLowerCase().includes(query.toLowerCase())
)
)
); );
return of(filteredBooks);
} }
getBookDataUrl(bookId: number): string { getBookDataUrl(bookId: number): string {
@@ -130,45 +150,39 @@ export class BookService {
} }
setBookMetadata(googleBookId: string, bookId: number): Observable<Book> { setBookMetadata(googleBookId: string, bookId: number): Observable<Book> {
const requestBody = {googleBookId: googleBookId}; const requestBody = { googleBookId };
return this.http.put<Book>(`${this.url}/${bookId}/set-metadata`, requestBody).pipe( return this.http.put<Book>(`${this.url}/${bookId}/set-metadata`, requestBody).pipe(
map(book => { map(book => {
const updatedBooks = this.books.getValue().map(existingBook => const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(existingBook =>
existingBook.id === book.id ? book : existingBook existingBook.id === book.id ? book : existingBook
); );
this.books.next(updatedBooks); this.bookStateSubject.next({ ...currentState, books: updatedBooks });
return book; return book;
}), }),
catchError(error => { catchError(error => {
console.error('Error assigning shelves to books:', error); const currentState = this.bookStateSubject.value;
this.bookStateSubject.next({ ...currentState, error: error.message });
throw error; throw error;
}) })
); );
} }
handleNewlyCreatedBook(book: Book): void { handleNewlyCreatedBook(book: Book): void {
const currentBooks = this.books.getValue(); const currentState = this.bookStateSubject.value;
const bookIndex = currentBooks.findIndex(existingBook => existingBook.id === book.id); const updatedBooks = currentState.books ? [...currentState.books] : [];
const updatedBooks = [...currentBooks]; const bookIndex = updatedBooks.findIndex(existingBook => existingBook.id === book.id);
if (bookIndex > -1) { if (bookIndex > -1) {
updatedBooks[bookIndex] = book; updatedBooks[bookIndex] = book;
} else { } else {
updatedBooks.push(book); updatedBooks.push(book);
} }
this.books.next(updatedBooks); this.bookStateSubject.next({ ...currentState, books: updatedBooks });
} }
handleRemovedBookIds(removedBookIds: Set<number>) { handleRemovedBookIds(removedBookIds: Set<number>): void {
console.log(removedBookIds); const currentState = this.bookStateSubject.value;
const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.has(book.id));
if (!(removedBookIds instanceof Set)) { this.bookStateSubject.next({ ...currentState, books: filteredBooks });
console.error("removedBookIds should be a Set");
return; // Or throw an error if preferred
}
const currentBooks = this.books.getValue();
let filteredBooks = currentBooks.filter(currentBook => !removedBookIds.has(currentBook.id));
this.books.next(filteredBooks);
} }
} }
@@ -1,39 +1,60 @@
import {Injectable} from '@angular/core'; import { Injectable } from '@angular/core';
import {BehaviorSubject, Observable, of, tap} from 'rxjs'; import { BehaviorSubject, Observable, of, tap } from 'rxjs';
import {HttpClient} from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import {catchError, map} from 'rxjs/operators'; import { catchError, map } from 'rxjs/operators';
import {Library} from '../model/library.model'; import { Library } from '../model/library.model';
import {BookService} from './book.service'; import { BookService } from './book.service';
import {BookWithNeighborsDTO} from '../model/book.model'; import { BookWithNeighborsDTO } from '../model/book.model';
import {SortOption} from '../model/sort.model'; import { SortOption } from '../model/sort.model';
import { LibraryState } from '../model/state/library-state.model';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class LibraryService { export class LibraryService {
private readonly url = 'http://localhost:8080/v1/library'; private readonly url = 'http://localhost:8080/v1/library';
private libraries = new BehaviorSubject<Library[]>([]);
libraries$ = this.libraries.asObservable(); private libraryStateSubject = new BehaviorSubject<LibraryState>({
libraries: null,
loaded: false,
error: null,
});
libraryState$ = this.libraryStateSubject.asObservable();
constructor(private http: HttpClient, private bookService: BookService) { constructor(private http: HttpClient, private bookService: BookService) {
this.loadLibraries();
}
private loadLibraries(): void {
this.http.get<Library[]>(this.url).pipe( this.http.get<Library[]>(this.url).pipe(
catchError(error => { catchError(error => {
this.libraryStateSubject.next({
libraries: null,
loaded: true,
error: error.message,
});
return of([]); return of([]);
}) })
).subscribe((libraries) => { ).subscribe(libraries => {
this.libraries.next(libraries); this.libraryStateSubject.next({
libraries,
loaded: true,
error: null,
});
}); });
} }
createLibrary(newLibrary: Library): Observable<Library> { createLibrary(newLibrary: Library): Observable<Library> {
return this.http.post<Library>(this.url, newLibrary).pipe( return this.http.post<Library>(this.url, newLibrary).pipe(
map((createdLibrary) => { map(createdLibrary => {
this.libraries.next([...this.libraries.value, createdLibrary]); const currentState = this.libraryStateSubject.value;
const updatedLibraries = currentState.libraries ? [...currentState.libraries, createdLibrary] : [createdLibrary];
this.libraryStateSubject.next({ ...currentState, libraries: updatedLibraries });
return createdLibrary; return createdLibrary;
}), }),
catchError((error) => { catchError(error => {
console.error('Error creating library:', error); const currentState = this.libraryStateSubject.value;
this.libraryStateSubject.next({ ...currentState, error: error.message });
throw error; throw error;
}) })
); );
@@ -43,30 +64,41 @@ export class LibraryService {
return this.http.delete<void>(`${this.url}/${libraryId}`).pipe( return this.http.delete<void>(`${this.url}/${libraryId}`).pipe(
tap(() => { tap(() => {
this.bookService.removeBooksByLibraryId(libraryId); this.bookService.removeBooksByLibraryId(libraryId);
const updatedLibraries = this.libraries.value.filter(library => library.id !== libraryId); const currentState = this.libraryStateSubject.value;
this.libraries.next(updatedLibraries); const updatedLibraries = currentState.libraries?.filter(library => library.id !== libraryId) || [];
this.libraryStateSubject.next({ ...currentState, libraries: updatedLibraries });
}), }),
catchError(error => { catchError(error => {
const currentState = this.libraryStateSubject.value;
this.libraryStateSubject.next({ ...currentState, error: error.message });
return of(); return of();
}) })
); );
} }
refreshLibrary(libraryId: number): Observable<void> { refreshLibrary(libraryId: number): Observable<void> {
return this.http.put<void>(`${this.url}/${libraryId}/refresh`, {}); return this.http.put<void>(`${this.url}/${libraryId}/refresh`, {}).pipe(
catchError(error => {
const currentState = this.libraryStateSubject.value;
this.libraryStateSubject.next({ ...currentState, error: error.message });
throw error;
})
);
} }
updateSort(libraryId: number, sort: SortOption): Observable<Library> { updateSort(libraryId: number, sort: SortOption): Observable<Library> {
return this.http.put<Library>(`${this.url}/${libraryId}/sort`, sort).pipe( return this.http.put<Library>(`${this.url}/${libraryId}/sort`, sort).pipe(
map(updatedLibrary => { map(updatedLibrary => {
const updatedShelves = this.libraries.value.map(library => const currentState = this.libraryStateSubject.value;
const updatedLibraries = currentState.libraries?.map(library =>
library.id === libraryId ? updatedLibrary : library library.id === libraryId ? updatedLibrary : library
); ) || [];
this.libraries.next(updatedShelves); this.libraryStateSubject.next({ ...currentState, libraries: updatedLibraries });
return updatedLibrary; return updatedLibrary;
}), }),
catchError(error => { catchError(error => {
console.error('Error updating library sort:', error); const currentState = this.libraryStateSubject.value;
this.libraryStateSubject.next({ ...currentState, error: error.message });
throw error; throw error;
}) })
); );
@@ -77,9 +109,8 @@ export class LibraryService {
} }
getBookCount(libraryId: number): Observable<number> { getBookCount(libraryId: number): Observable<number> {
return this.bookService.books$.pipe( return this.bookService.bookState$.pipe(
map(books => books.filter(book => book.libraryId === libraryId).length) map(state => (state.books || []).filter(book => book.libraryId === libraryId).length)
); );
} }
} }
@@ -1,38 +1,58 @@
import {Injectable} from '@angular/core'; import { Injectable } from '@angular/core';
import {BehaviorSubject, Observable, of, tap} from 'rxjs'; import { BehaviorSubject, Observable, of, tap } from 'rxjs';
import {catchError, map} from 'rxjs/operators'; import { catchError, map } from 'rxjs/operators';
import {HttpClient} from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import {Shelf} from '../model/shelf.model'; import { Shelf } from '../model/shelf.model';
import {SortOption} from '../model/sort.model'; import { SortOption } from '../model/sort.model';
import {BookService} from "./book.service"; import { BookService } from './book.service';
import { ShelfState } from '../model/state/shelf-state.model';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class ShelfService { export class ShelfService {
private readonly url = 'http://localhost:8080/v1/shelf'; private readonly url = 'http://localhost:8080/v1/shelf';
private shelves = new BehaviorSubject<Shelf[]>([]); private shelfStateSubject = new BehaviorSubject<ShelfState>({
shelves$ = this.shelves.asObservable(); shelves: null,
loaded: false,
error: null,
});
shelfState$ = this.shelfStateSubject.asObservable();
constructor(private http: HttpClient, private bookService: BookService) { constructor(private http: HttpClient, private bookService: BookService) {
this.loadShelves();
}
private loadShelves(): void {
this.http.get<Shelf[]>(this.url).pipe( this.http.get<Shelf[]>(this.url).pipe(
catchError(error => { catchError(error => {
this.shelfStateSubject.next({
shelves: null,
loaded: true,
error: error.message,
});
return of([]); return of([]);
}) })
).subscribe((shelves) => { ).subscribe(shelves => {
this.shelves.next(shelves); this.shelfStateSubject.next({
shelves,
loaded: true,
error: null,
});
}); });
} }
createShelf(shelf: Shelf): Observable<Shelf> { createShelf(shelf: Shelf): Observable<Shelf> {
return this.http.post<Shelf>(this.url, shelf).pipe( return this.http.post<Shelf>(this.url, shelf).pipe(
map(newShelf => { map(newShelf => {
this.shelves.next([...this.shelves.value, newShelf]) const currentState = this.shelfStateSubject.value;
const updatedShelves = currentState.shelves ? [...currentState.shelves, newShelf] : [newShelf];
this.shelfStateSubject.next({ ...currentState, shelves: updatedShelves });
return newShelf; return newShelf;
}), }),
catchError(error => { catchError(error => {
console.error('Error creating shelf:', error); const currentState = this.shelfStateSubject.value;
this.shelfStateSubject.next({ ...currentState, error: error.message });
throw error; throw error;
}) })
); );
@@ -41,35 +61,42 @@ export class ShelfService {
updateSort(shelfId: number, sort: SortOption): Observable<Shelf> { updateSort(shelfId: number, sort: SortOption): Observable<Shelf> {
return this.http.put<Shelf>(`${this.url}/${shelfId}/sort`, sort).pipe( return this.http.put<Shelf>(`${this.url}/${shelfId}/sort`, sort).pipe(
map(updatedShelf => { map(updatedShelf => {
const updatedShelves = this.shelves.value.map(shelf => const currentState = this.shelfStateSubject.value;
const updatedShelves = currentState.shelves?.map(shelf =>
shelf.id === shelfId ? updatedShelf : shelf shelf.id === shelfId ? updatedShelf : shelf
); ) || [];
this.shelves.next(updatedShelves); this.shelfStateSubject.next({ ...currentState, shelves: updatedShelves });
return updatedShelf; return updatedShelf;
}), }),
catchError(error => { catchError(error => {
console.error('Error updating shelf sort:', error); const currentState = this.shelfStateSubject.value;
this.shelfStateSubject.next({ ...currentState, error: error.message });
throw error; throw error;
}) })
); );
} }
deleteShelf(shelfId: number) { deleteShelf(shelfId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${shelfId}`).pipe( return this.http.delete<void>(`${this.url}/${shelfId}`).pipe(
tap(() => { tap(() => {
this.bookService.removeBooksByLibraryId(shelfId); this.bookService.removeBooksFromShelf(shelfId);
let shelves = this.shelves.value.filter(shelf => shelf.id !== shelfId); const currentState = this.shelfStateSubject.value;
this.shelves.next(shelves); const updatedShelves = currentState.shelves?.filter(shelf => shelf.id !== shelfId) || [];
this.shelfStateSubject.next({ ...currentState, shelves: updatedShelves });
}), }),
catchError(error => { catchError(error => {
const currentState = this.shelfStateSubject.value;
this.shelfStateSubject.next({ ...currentState, error: error.message });
return of(); return of();
}) })
); );
} }
getBookCount(shelfId: number): Observable<number> { getBookCount(shelfId: number): Observable<number> {
return this.bookService.books$.pipe( return this.bookService.bookState$.pipe(
map(books => books.filter(book => book.shelves?.some(shelf => shelf.id === shelfId)).length) map(state =>
(state.books || []).filter(book => book.shelves?.some(shelf => shelf.id === shelfId)).length
)
); );
} }
} }