Sorting works with the BE! Yay! Need to improve the the code though

This commit is contained in:
aditya.chandel
2024-12-25 18:17:40 -07:00
parent affdcb95c6
commit 383a3189bb
9 changed files with 117 additions and 102 deletions
@@ -4,17 +4,13 @@ import com.adityachandel.booklore.model.dto.BookDTO;
import com.adityachandel.booklore.model.dto.BookWithNeighborsDTO;
import com.adityachandel.booklore.model.dto.LibraryDTO;
import com.adityachandel.booklore.model.dto.request.CreateLibraryRequest;
import com.adityachandel.booklore.model.entity.Sort;
import com.adityachandel.booklore.service.BooksService;
import com.adityachandel.booklore.service.LibraryService;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.util.List;
@@ -62,4 +58,9 @@ public class LibraryController {
List<BookDTO> books = libraryService.getBooks(libraryId);
return ResponseEntity.ok(books);
}
@PutMapping("/{libraryId}/sort")
public ResponseEntity<LibraryDTO> updateLibrary(@PathVariable long libraryId, @RequestBody Sort sort) {
return ResponseEntity.ok(libraryService.updateSort(libraryId, sort));
}
}
@@ -13,7 +13,7 @@ public class SortConverter implements AttributeConverter<Sort, String> {
if (sort == null) {
return null;
}
return sort.getSortField() + "," + sort.getSortDirection().name();
return sort.getField() + "," + sort.getDirection().name();
}
@Override
@@ -23,8 +23,8 @@ public class SortConverter implements AttributeConverter<Sort, String> {
}
String[] parts = dbData.split(",");
Sort sort = new Sort();
sort.setSortField(parts[0]);
sort.setSortDirection(SortDirection.valueOf(parts[1]));
sort.setField(parts[0]);
sort.setDirection(SortDirection.valueOf(parts[1]));
return sort;
}
}
@@ -5,6 +5,6 @@ import lombok.Data;
@Data
public class Sort {
private String sortField;
private SortDirection sortDirection;
private String field;
private SortDirection direction;
}
@@ -6,6 +6,7 @@ import com.adityachandel.booklore.model.dto.LibraryDTO;
import com.adityachandel.booklore.model.dto.request.CreateLibraryRequest;
import com.adityachandel.booklore.model.entity.Book;
import com.adityachandel.booklore.model.entity.Library;
import com.adityachandel.booklore.model.entity.Sort;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.transformer.BookTransformer;
@@ -13,8 +14,6 @@ import com.adityachandel.booklore.transformer.LibraryTransformer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.io.IOException;
@@ -78,4 +77,10 @@ public class LibraryService {
List<Book> books = bookRepository.findBooksByLibraryId(libraryId);
return books.stream().map(BookTransformer::convertToBookDTO).toList();
}
public LibraryDTO updateSort(long libraryId, Sort sort) {
Library library = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
library.setSort(sort);
return LibraryTransformer.convertToLibraryDTO(libraryRepository.save(library));
}
}
@@ -30,11 +30,12 @@ export class BooksBrowserComponent implements OnInit {
entity: Library | Shelf | null = null;
entityType: string = '';
selectedSort: SortOption | null = null;
sortOptions: SortOption[] = [
{label: '↑ Title', field: 'title', direction: 'ascending'},
{label: '↓ Title', field: 'title', direction: 'descending'},
{label: '↑ Published Date', field: 'publishedDate', direction: 'ascending'},
{label: '↓ Published Date', field: 'publishedDate', direction: 'descending'}
{label: '↑ Title', field: 'title', direction: 'ASCENDING'},
{label: '↓ Title', field: 'title', direction: 'DESCENDING'},
{label: '↑ Published Date', field: 'publishedDate', direction: 'ASCENDING'},
{label: '↓ Published Date', field: 'publishedDate', direction: 'DESCENDING'}
];
constructor(
@@ -45,11 +46,21 @@ export class BooksBrowserComponent implements OnInit {
private libraryService: LibraryService,
private bookService: BookService,
private shelfService: ShelfService,
private dialogService: DialogService,
private sortService: SortService
private dialogService: DialogService
) {
}
private setSelectedSortFromEntity(entity: Library | Shelf | null): void {
if (entity?.sort) {
const {field, direction} = entity.sort;
this.selectedSort = this.sortOptions.find(
option => option.field === field && option.direction === direction
) || null;
} else {
this.selectedSort = null;
}
}
ngOnInit(): void {
const routeParam$ = this.activatedRoute.paramMap.pipe(
map(params => {
@@ -73,40 +84,12 @@ export class BooksBrowserComponent implements OnInit {
this.entity$.subscribe(entity => {
this.entity = entity;
});
routeParam$.subscribe(({libraryId, shelfId}) => {
this.handleSortingState(libraryId, shelfId);
this.setSelectedSortFromEntity(entity);
});
this.setupMenu();
}
private handleSortingState(libraryId: number, shelfId: number): void {
let entityType: string | null = null;
let entityId: number | null = null;
if (libraryId) {
entityType = 'Library';
entityId = libraryId;
} else if (shelfId) {
entityType = 'Shelf';
entityId = shelfId;
}
if (entityType && entityId !== null) {
const key = this.sortService.generateKey(entityType, entityId);
if (key) {
const storedSort = this.sortService.getSortOption(key);
if (storedSort) {
this.selectedSort = storedSort;
} else {
this.selectedSort = null;
}
}
}
}
private fetchEntityType(libraryId: number, shelfId: number): Observable<string> {
if (!isNaN(libraryId) && libraryId !== 0) {
this.entityType = 'Library';
@@ -119,16 +102,17 @@ export class BooksBrowserComponent implements OnInit {
}
private fetchBooks(libraryId: number, shelfId: number): Observable<Book[]> {
if (libraryId) {
return this.bookService.books$.pipe(
map(books => books.filter(book => book.libraryId === libraryId))
);
} else if (shelfId) {
return this.bookService.books$.pipe(
map(books => books.filter(book => book.shelves?.some(shelf => shelf.id === shelfId)))
);
}
return of([]);
return this.bookService.books$.pipe(
map(books => {
let filteredBooks = books;
if (libraryId) {
filteredBooks = books.filter(book => book.libraryId === libraryId);
} else if (shelfId) {
filteredBooks = books.filter(book => book.shelves?.some(shelf => shelf.id === shelfId));
}
return this.applySort(filteredBooks);
})
);
}
private fetchEntity(libraryId: number, shelfId: number): Observable<Library | Shelf | null> {
@@ -167,31 +151,26 @@ export class BooksBrowserComponent implements OnInit {
];
}
sortBooks(): void {
if (this.books$ && this.selectedSort) {
this.books$ = this.books$.pipe(
map(books => {
return books.sort((a, b) => {
const field = this.selectedSort?.field;
const direction = this.selectedSort?.direction;
let valueA: any, valueB: any;
if (field === 'title') {
valueA = a.metadata?.title?.toLowerCase() || '';
valueB = b.metadata?.title?.toLowerCase() || '';
} else if (field === 'publishedDate') {
valueA = new Date(a.metadata?.publishedDate || 0).getTime();
valueB = new Date(b.metadata?.publishedDate || 0).getTime();
}
if (valueA === undefined || valueB === undefined) return 0;
if (direction === 'ascending') {
return valueA < valueB ? -1 : valueA > valueB ? 1 : 0;
} else {
return valueA > valueB ? -1 : valueA < valueB ? 1 : 0;
}
});
})
);
}
private applySort(books: Book[]): Book[] {
if (!this.selectedSort) return books;
const {field, direction} = this.selectedSort;
return books.sort((a, b) => {
let valueA: any, valueB: any;
if (field === 'title') {
valueA = a.metadata?.title?.toLowerCase() || '';
valueB = b.metadata?.title?.toLowerCase() || '';
} else if (field === 'publishedDate') {
valueA = new Date(a.metadata?.publishedDate || 0).getTime();
valueB = new Date(b.metadata?.publishedDate || 0).getTime();
}
if (valueA === undefined || valueB === undefined) return 0;
if (direction === 'ASCENDING') {
return valueA < valueB ? -1 : valueA > valueB ? 1 : 0;
} else {
return valueA > valueB ? -1 : valueA < valueB ? 1 : 0;
}
});
}
deselectAllBooks(): void {
@@ -232,11 +211,19 @@ export class BooksBrowserComponent implements OnInit {
}
updateSortOption(sortOption: SortOption): void {
const key = this.sortService.generateKey(this.entityType, this.entity?.id!);
if (key) {
this.sortService.setSortOption(key, sortOption);
this.selectedSort = sortOption;
this.sortBooks();
this.selectedSort = sortOption;
this.books$ = this.activatedRoute.paramMap.pipe(
map(params => {
const libraryId = Number(params.get('libraryId'));
const shelfId = Number(params.get('shelfId'));
return {libraryId, shelfId};
}),
switchMap(({libraryId, shelfId}) => this.fetchBooks(libraryId, shelfId))
);
if (this.entityType === 'Library') {
this.libraryService.updateSort(this.entity?.id!, sortOption).subscribe();
} else if (this.entityType === 'Shelf') {
this.shelfService.updateSort(this.entity?.id!, sortOption).subscribe();
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
export interface Sort {
name: string;
field: string;
direction: string;
}
@@ -1,10 +1,11 @@
import {Injectable, OnInit} from '@angular/core';
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable, of, tap} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {catchError, map} from 'rxjs/operators';
import {Library} from '../model/library.model';
import {BookService} from './book.service';
import {BookWithNeighborsDTO} from '../model/book.model';
import {Sort} from '../model/sort.model';
@Injectable({
providedIn: 'root'
@@ -51,6 +52,22 @@ export class LibraryService {
);
}
updateSort(libraryId: number, sort: Sort): Observable<Library> {
return this.http.put<Library>(`${this.url}/${libraryId}/sort`, sort).pipe(
map(updatedLibrary => {
const updatedShelves = this.libraries.value.map(library =>
library.id === libraryId ? updatedLibrary : library
);
this.libraries.next(updatedShelves);
return updatedLibrary;
}),
catchError(error => {
console.error('Error updating library sort:', error);
throw error;
})
);
}
getBookWithNeighbours(libraryId: number, bookId: number): Observable<BookWithNeighborsDTO> {
return this.http.get<BookWithNeighborsDTO>(`${this.url}/${libraryId}/book/${bookId}/withNeighbors`);
}
@@ -3,6 +3,7 @@ import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
import {HttpClient} from '@angular/common/http';
import {Shelf} from '../model/shelf.model';
import {Sort} from '../model/sort.model';
@Injectable({
providedIn: 'root'
@@ -35,4 +36,21 @@ export class ShelfService {
})
);
}
updateSort(shelfId: number, sort: Sort): Observable<Shelf> {
return this.http.put<Shelf>(`${this.url}/${shelfId}/sort`, { shelfId, sort }).pipe(
map(updatedShelf => {
const updatedShelves = this.shelves.value.map(shelf =>
shelf.id === shelfId ? updatedShelf : shelf
);
this.shelves.next(updatedShelves);
return updatedShelf;
}),
catchError(error => {
console.error('Error updating shelf sort:', error);
throw error;
})
);
}
}
@@ -5,21 +5,8 @@ import { SortOption } from '../model/sort-option.model';
providedIn: 'root',
})
export class SortService {
private selectedSorts: { [key: string]: SortOption | null } = {};
generateKey(entityType: string, entityId: number): string {
if (entityType && entityId) {
return `${entityType.toLowerCase()}-${entityId}`;
}
return '';
}
getSortOption(key: string): SortOption | null {
return this.selectedSorts[key] || null;
}
setSortOption(key: string, sortOption: SortOption): void {
this.selectedSorts[key] = sortOption;
}
}