refactor(books): add /api/v1/books/facets endpoint (#1898)
This commit is contained in:
@@ -1,11 +1,12 @@
|
||||
package org.booklore.browse;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import tools.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record Link(List<String> rel, String href, String type) {
|
||||
public record Link(@JsonSerialize(using = RelSerializer.class) List<String> rel, String href, String type) {
|
||||
|
||||
public static final String JSON_TYPE = "application/json";
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ import org.springframework.stereotype.Component;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
// Builds the paging links for a browse page (self/first/previous/next)
|
||||
// Each carries the request's facet/query params + a cursor offset
|
||||
// Builds the links for a browse page (self/first/previous/next/facet)
|
||||
// Paging links carry the request's facet/query params + a cursor offset
|
||||
@Component
|
||||
public class LinksBuilder {
|
||||
|
||||
@@ -18,6 +18,7 @@ public class LinksBuilder {
|
||||
|
||||
public record Context(
|
||||
String pagePath,
|
||||
String facetPath,
|
||||
String preservedQuery,
|
||||
long offset,
|
||||
int limit,
|
||||
@@ -28,6 +29,11 @@ public class LinksBuilder {
|
||||
|
||||
public List<Link> build(Context ctx) {
|
||||
List<Link> links = new ArrayList<>();
|
||||
String facetHref = ctx.facetPath();
|
||||
if (ctx.preservedQuery() != null && !ctx.preservedQuery().isBlank()) {
|
||||
facetHref = facetHref + "?" + ctx.preservedQuery();
|
||||
}
|
||||
links.add(Link.json(List.of("facet"), facetHref));
|
||||
links.add(pageLink(List.of("self"), ctx, ctx.offset()));
|
||||
links.add(pageLink(List.of("first"), ctx, 0));
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.booklore.browse;
|
||||
|
||||
import tools.jackson.core.JsonGenerator;
|
||||
import tools.jackson.databind.SerializationContext;
|
||||
import tools.jackson.databind.ValueSerializer;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
// Serializes rel following the RWPM Link Object convention used by the OPDS 2.0
|
||||
// examples: a bare string for a single relation, an array for several.
|
||||
public class RelSerializer extends ValueSerializer<List<String>> {
|
||||
|
||||
@Override
|
||||
public void serialize(List<String> rels, JsonGenerator gen, SerializationContext context) {
|
||||
if (rels.size() == 1) {
|
||||
gen.writeString(rels.getFirst());
|
||||
return;
|
||||
}
|
||||
gen.writeStartArray();
|
||||
for (String rel : rels) {
|
||||
gen.writeString(rel);
|
||||
}
|
||||
gen.writeEndArray();
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,8 @@ import org.booklore.service.book.BookUpdateService;
|
||||
import org.booklore.service.book.DuplicateDetectionService;
|
||||
import org.booklore.service.book.PhysicalBookService;
|
||||
import org.booklore.service.browse.BookBrowseService;
|
||||
import org.booklore.service.browse.BookFacetService;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse;
|
||||
import org.booklore.service.metadata.BookMetadataService;
|
||||
import org.booklore.service.progress.ReadingProgressService;
|
||||
import org.booklore.service.recommender.BookRecommendationService;
|
||||
@@ -61,6 +63,7 @@ public class BookController {
|
||||
|
||||
private final BookService bookService;
|
||||
private final BookBrowseService bookBrowseService;
|
||||
private final BookFacetService bookFacetService;
|
||||
private final BookUpdateService bookUpdateService;
|
||||
private final BookRecommendationService bookRecommendationService;
|
||||
private final BookFileAttachmentService bookFileAttachmentService;
|
||||
@@ -102,6 +105,19 @@ public class BookController {
|
||||
return ResponseEntity.ok(bookBrowseService.wrapLegacy(bookService.getBookDTOsPaged(pageable), pageable));
|
||||
}
|
||||
|
||||
@Operation(summary = "Get book facets", description = "Available facet values and counts for the current user, scoped by the same facet, facet_logic, and query parameters as the page endpoint. Each facet omits its own selections from its counts.")
|
||||
@ApiResponse(responseCode = "200", description = "Facet groups returned successfully")
|
||||
@GetMapping("/facets")
|
||||
public ResponseEntity<FacetGroupsResponse> getBookFacets(
|
||||
@Parameter(description = "Facet selection in key:value form; repeatable")
|
||||
@RequestParam(required = false) List<String> facet,
|
||||
@Parameter(description = "How facet values combine within a group: and, or, or not")
|
||||
@RequestParam(name = "facet_logic", required = false) String facetLogic,
|
||||
@Parameter(description = "Free-text search applied to the counts")
|
||||
@RequestParam(required = false) String query) {
|
||||
return ResponseEntity.ok(bookFacetService.getFacets(facet, facetLogic, query));
|
||||
}
|
||||
|
||||
@Operation(summary = "Get a book by ID", description = "Retrieve details of a specific book by its ID.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Book details returned successfully"),
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.booklore.model.dto.browse;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import tools.jackson.databind.annotation.JsonSerialize;
|
||||
import org.booklore.browse.Link;
|
||||
import org.booklore.browse.RelSerializer;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record FacetGroupsResponse(List<Link> links, List<FacetGroup> facets) {
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record FacetGroup(Metadata metadata, List<FacetLink> links) {
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record Metadata(String rel, String key, String title) {
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record FacetLink(@JsonSerialize(using = RelSerializer.class) List<String> rel, String href, String type, String title, String value, Properties properties) {
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record Properties(Long numberOfItems) {
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ import java.util.stream.Collectors;
|
||||
public class BookBrowseService {
|
||||
|
||||
private static final String PAGE_PATH = "/api/v1/books/page";
|
||||
private static final String FACET_PATH = "/api/v1/books/facets";
|
||||
private static final int MAX_PAGE_SIZE = 100;
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
@@ -86,7 +87,7 @@ public class BookBrowseService {
|
||||
CursorState baseState = new CursorState(offset, limit, sortString, paramsHash);
|
||||
String currentCursor = cursorCodec.encode(baseState);
|
||||
List<Link> links = linksBuilder.build(new LinksBuilder.Context(
|
||||
PAGE_PATH, BrowseParams.preserved(facet, facetLogicParam, query), offset, limit, page.getTotalElements(), baseState));
|
||||
PAGE_PATH, FACET_PATH, BrowseParams.preserved(facet, facetLogicParam, query), offset, limit, page.getTotalElements(), baseState));
|
||||
|
||||
return BrowsePage.of(page.getContent(), offset, limit, page.getTotalElements(), currentCursor, links);
|
||||
}
|
||||
@@ -97,7 +98,7 @@ public class BookBrowseService {
|
||||
String paramsHash = ParamsHash.compute(null, Map.of(), FacetLogic.AND);
|
||||
CursorState baseState = new CursorState(offset, limit, null, paramsHash);
|
||||
List<Link> links = linksBuilder.build(new LinksBuilder.Context(
|
||||
PAGE_PATH, "", offset, limit, page.getTotalElements(), baseState));
|
||||
PAGE_PATH, FACET_PATH, "", offset, limit, page.getTotalElements(), baseState));
|
||||
return BrowsePage.of(page.getContent(), offset, limit, page.getTotalElements(), cursorCodec.encode(baseState), links);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import jakarta.persistence.Tuple;
|
||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
import jakarta.persistence.criteria.Expression;
|
||||
import jakarta.persistence.criteria.Join;
|
||||
import jakarta.persistence.criteria.JoinType;
|
||||
import jakarta.persistence.criteria.Predicate;
|
||||
import jakarta.persistence.criteria.Root;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.booklore.browse.FacetLogic;
|
||||
import org.booklore.browse.Link;
|
||||
import org.booklore.browse.ParamsHash;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetGroup;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetLink;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse.Metadata;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse.Properties;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(readOnly = true)
|
||||
public class BookFacetService {
|
||||
|
||||
private static final String PAGE_PATH = "/api/v1/books/page";
|
||||
private static final String FACET_PATH = "/api/v1/books/facets";
|
||||
private static final int MAX_VALUES = 100;
|
||||
|
||||
private static final List<FacetDef> FACETS = List.of(
|
||||
new FacetDef("author", "Authors", root -> metadata(root).join("authors", JoinType.LEFT).get("name")),
|
||||
new FacetDef("genre", "Genre", root -> metadata(root).join("categories", JoinType.LEFT).get("name")),
|
||||
new FacetDef("tag", "Tags", root -> metadata(root).join("tags", JoinType.LEFT).get("name")),
|
||||
new FacetDef("mood", "Moods", root -> metadata(root).join("moods", JoinType.LEFT).get("name")),
|
||||
new FacetDef("series", "Series", root -> metadata(root).get("seriesName")),
|
||||
new FacetDef("publisher", "Publisher", root -> metadata(root).get("publisher")),
|
||||
new FacetDef("language", "Language", root -> metadata(root).get("language")),
|
||||
new FacetDef("narrator", "Narrator", root -> metadata(root).get("narrator")),
|
||||
new FacetDef("file_type", "File Type", root -> root.join("bookFiles", JoinType.LEFT).get("bookType")));
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
private final BookFilterSpecifications filterSpecifications;
|
||||
private final BookSortRegistry sortRegistry;
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
private final Cache<String, FacetGroupsResponse> cache = Caffeine.newBuilder()
|
||||
.expireAfterWrite(Duration.ofSeconds(30))
|
||||
.maximumSize(200)
|
||||
.build();
|
||||
|
||||
public FacetGroupsResponse getFacets(List<String> facet, String facetLogicParam, String query) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Long userId = user.getId();
|
||||
boolean isAdmin = user.getPermissions().isAdmin();
|
||||
Set<Long> libraryIds = BookFilterSpecifications.libraryIds(user);
|
||||
|
||||
Map<String, List<String>> facets = BookFilterSpecifications.parseFacets(facet);
|
||||
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
|
||||
|
||||
String cacheKey = userId + ":" + ParamsHash.compute(query, facets, facetLogic);
|
||||
return cache.get(cacheKey, key -> {
|
||||
String preserved = BrowseParams.preserved(facet, facetLogicParam, query);
|
||||
List<FacetGroup> groups = new ArrayList<>();
|
||||
groups.add(sortGroup(preserved));
|
||||
for (FacetDef def : FACETS) {
|
||||
Specification<BookEntity> base = filterSpecifications.base(query, facets, facetLogic, userId, isAdmin, libraryIds, def.key());
|
||||
groups.add(toGroup(def, count(def, base), facet, preserved));
|
||||
}
|
||||
List<Link> links = List.of(Link.json(List.of("self"), href(FACET_PATH, preserved)));
|
||||
return new FacetGroupsResponse(links, groups);
|
||||
});
|
||||
}
|
||||
|
||||
// Package-private: lets tests reset the shared singleton cache between runs.
|
||||
void clearCache() {
|
||||
cache.invalidateAll();
|
||||
}
|
||||
|
||||
private List<FacetCount> count(FacetDef def, Specification<BookEntity> base) {
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
|
||||
Root<BookEntity> root = cq.from(BookEntity.class);
|
||||
Expression<?> value = def.value().apply(root);
|
||||
Expression<Long> count = cb.countDistinct(root.get("id"));
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
Predicate basePredicate = base.toPredicate(root, cq, cb);
|
||||
if (basePredicate != null) {
|
||||
predicates.add(basePredicate);
|
||||
}
|
||||
predicates.add(cb.isNotNull(value));
|
||||
|
||||
cq.multiselect(value.alias("value"), count.alias("count"));
|
||||
cq.where(predicates.toArray(Predicate[]::new));
|
||||
cq.groupBy(value);
|
||||
cq.orderBy(cb.desc(count), cb.asc(value));
|
||||
|
||||
return entityManager.createQuery(cq).setMaxResults(MAX_VALUES).getResultList().stream()
|
||||
.map(tuple -> new FacetCount(String.valueOf(tuple.get("value")), ((Number) tuple.get("count")).longValue()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private FacetGroup toGroup(FacetDef def, List<FacetCount> counts, List<String> facet, String preserved) {
|
||||
List<FacetLink> links = counts.stream()
|
||||
.map(c -> {
|
||||
boolean active = BrowseParams.hasFacet(facet, def.key(), c.value());
|
||||
List<String> rel = active ? List.of("self", "facet") : List.of("facet");
|
||||
String href = active
|
||||
? href(PAGE_PATH, preserved)
|
||||
: pageLink(preserved, "facet=" + BrowseParams.encode(def.key() + ":" + c.value()));
|
||||
return new FacetLink(rel, href, Link.JSON_TYPE, c.value(), c.value(), new Properties(c.count()));
|
||||
})
|
||||
.toList();
|
||||
return new FacetGroup(new Metadata("facet", def.key(), def.title()), links);
|
||||
}
|
||||
|
||||
private FacetGroup sortGroup(String preserved) {
|
||||
List<FacetLink> links = new ArrayList<>();
|
||||
for (String key : sortRegistry.registry().keys()) {
|
||||
if (key.equals("id")) {
|
||||
continue;
|
||||
}
|
||||
links.add(new FacetLink(List.of("sort"), pageLink(preserved, "sort=" + BrowseParams.encode(key)), Link.JSON_TYPE, key + " ascending", key, null));
|
||||
links.add(new FacetLink(List.of("sort"), pageLink(preserved, "sort=-" + BrowseParams.encode(key)), Link.JSON_TYPE, key + " descending", "-" + key, null));
|
||||
}
|
||||
return new FacetGroup(new Metadata("sort", "sort", "Sort"), links);
|
||||
}
|
||||
|
||||
private static String pageLink(String preserved, String param) {
|
||||
return preserved.isBlank() ? PAGE_PATH + "?" + param : PAGE_PATH + "?" + preserved + "&" + param;
|
||||
}
|
||||
|
||||
private static String href(String path, String preserved) {
|
||||
return preserved.isBlank() ? path : path + "?" + preserved;
|
||||
}
|
||||
|
||||
private static Join<?, ?> metadata(Root<BookEntity> root) {
|
||||
return root.join("metadata", JoinType.LEFT);
|
||||
}
|
||||
|
||||
private record FacetDef(String key, String title, Function<Root<BookEntity>, Expression<?>> value) {
|
||||
}
|
||||
|
||||
private record FacetCount(String value, long count) {
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,24 @@ final class BrowseParams {
|
||||
return String.join("&", parts);
|
||||
}
|
||||
|
||||
static boolean hasFacet(List<String> facet, String key, String value) {
|
||||
if (facet == null) {
|
||||
return false;
|
||||
}
|
||||
return facet.stream().anyMatch(entry -> matchesFacet(entry, key, value));
|
||||
}
|
||||
|
||||
private static boolean matchesFacet(String entry, String key, String value) {
|
||||
if (entry == null) {
|
||||
return false;
|
||||
}
|
||||
int colon = entry.indexOf(':');
|
||||
if (colon <= 0 || colon == entry.length() - 1) {
|
||||
return false;
|
||||
}
|
||||
return entry.substring(0, colon).equals(key) && entry.substring(colon + 1).equalsIgnoreCase(value);
|
||||
}
|
||||
|
||||
static String encode(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ class LinksBuilderTest {
|
||||
|
||||
private LinksBuilder.Context context(long offset, int limit, long total, String preservedQuery) {
|
||||
CursorState base = new CursorState(offset, limit, "title", "hash00000000");
|
||||
return new LinksBuilder.Context("/api/v1/books/page", preservedQuery, offset, limit, total, base);
|
||||
return new LinksBuilder.Context("/api/v1/books/page", "/api/v1/books/facets", preservedQuery, offset, limit, total, base);
|
||||
}
|
||||
|
||||
private boolean hasRel(List<Link> links, String rel) {
|
||||
@@ -31,12 +31,27 @@ class LinksBuilderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void selfAndFirstAlwaysPresent() {
|
||||
void alwaysIncludesFacetSelfAndFirst() {
|
||||
List<Link> links = builder.build(context(40, 20, 100, ""));
|
||||
assertTrue(hasRel(links, "facet"));
|
||||
assertTrue(hasRel(links, "self"));
|
||||
assertTrue(hasRel(links, "first"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void facetLinkPointsAtFacetsEndpointWithoutCursor() {
|
||||
Link facet = withRel(builder.build(context(0, 20, 100, "")), "facet");
|
||||
assertEquals("/api/v1/books/facets", facet.href());
|
||||
assertEquals(Link.JSON_TYPE, facet.type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void facetLinkCarriesPreservedQuery() {
|
||||
Link facet = withRel(builder.build(context(0, 20, 100, "facet=genre%3AFiction")), "facet");
|
||||
assertEquals("/api/v1/books/facets?facet=genre%3AFiction", facet.href());
|
||||
assertEquals(Link.JSON_TYPE, facet.type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstPageOmitsPreviousButHasNext() {
|
||||
List<Link> links = builder.build(context(0, 20, 100, ""));
|
||||
@@ -111,7 +126,7 @@ class LinksBuilderTest {
|
||||
@Test
|
||||
void nullPreservedQueryStillProducesValidLinks() {
|
||||
List<Link> links = builder.build(new LinksBuilder.Context(
|
||||
"/api/v1/books/page", null, 0, 20, 5,
|
||||
"/api/v1/books/page", "/api/v1/books/facets", null, 0, 20, 5,
|
||||
new CursorState(0, 20, "title", "hash00000000")));
|
||||
assertTrue(hasRel(links, "self"));
|
||||
Link self = withRel(links, "self");
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package org.booklore.browse;
|
||||
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetLink;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse.Properties;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
// Uses the Jackson 3 (tools.jackson) mapper, the one Spring Boot wires into HTTP
|
||||
// message conversion; a Jackson 2 mapper would ignore the rel serializer entirely.
|
||||
class RelSerializerTest {
|
||||
|
||||
private final ObjectMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
@Test
|
||||
void emptyRelSerializesAsEmptyArray() {
|
||||
String json = mapper.writeValueAsString(Link.json(List.of(), "/api/v1/books/facets"));
|
||||
assertThat(json).isEqualTo("{\"rel\":[],\"href\":\"/api/v1/books/facets\",\"type\":\"application/json\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleRelSerializesAsString() {
|
||||
String json = mapper.writeValueAsString(Link.json(List.of("self"), "/api/v1/books/facets"));
|
||||
assertThat(json).isEqualTo("{\"rel\":\"self\",\"href\":\"/api/v1/books/facets\",\"type\":\"application/json\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void multipleRelsSerializeAsArray() {
|
||||
String json = mapper.writeValueAsString(Link.json(List.of("first", "previous"), "/api/v1/books/page"));
|
||||
assertThat(json).isEqualTo("{\"rel\":[\"first\",\"previous\"],\"href\":\"/api/v1/books/page\",\"type\":\"application/json\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void facetLinkFollowsTheSameConvention() {
|
||||
FacetLink inactive = new FacetLink(List.of("facet"), "/x", Link.JSON_TYPE, "Horror", "Horror", new Properties(2L));
|
||||
assertThat(mapper.writeValueAsString(inactive))
|
||||
.isEqualTo("{\"rel\":\"facet\",\"href\":\"/x\",\"type\":\"application/json\",\"title\":\"Horror\",\"value\":\"Horror\",\"properties\":{\"numberOfItems\":2}}");
|
||||
|
||||
FacetLink active = new FacetLink(List.of("self", "facet"), "/x", Link.JSON_TYPE, "Horror", "Horror", new Properties(2L));
|
||||
assertThat(mapper.writeValueAsString(active))
|
||||
.isEqualTo("{\"rel\":[\"self\",\"facet\"],\"href\":\"/x\",\"type\":\"application/json\",\"title\":\"Horror\",\"value\":\"Horror\",\"properties\":{\"numberOfItems\":2}}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import org.booklore.BookloreApplication;
|
||||
import org.booklore.browse.Link;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetGroup;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetLink;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.BookMetadataEntity;
|
||||
import org.booklore.model.entity.CategoryEntity;
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.service.task.TaskCronService;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SpringBootTest(classes = BookloreApplication.class)
|
||||
@Transactional
|
||||
@TestPropertySource(properties = {
|
||||
"spring.flyway.enabled=false",
|
||||
"spring.jpa.hibernate.ddl-auto=create-drop",
|
||||
"spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
|
||||
"spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect",
|
||||
"spring.datasource.url=jdbc:h2:mem:facettest;DB_CLOSE_DELAY=-1;NON_KEYWORDS=VALUE",
|
||||
"spring.datasource.driver-class-name=org.h2.Driver",
|
||||
"spring.datasource.username=sa",
|
||||
"spring.datasource.password=",
|
||||
"app.path-config=build/tmp/test-config",
|
||||
"app.bookdrop-folder=build/tmp/test-bookdrop",
|
||||
"spring.main.allow-bean-definition-overriding=true",
|
||||
"spring.task.scheduling.enabled=false",
|
||||
"app.task.scan-library-cron=*/1 * * * * *",
|
||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||
"app.features.oidc-enabled=false"
|
||||
})
|
||||
@Import(BookFacetServiceTest.TestConfig.class)
|
||||
class BookFacetServiceTest {
|
||||
|
||||
@Autowired
|
||||
private BookFacetService facetService;
|
||||
@Autowired
|
||||
private ObjectMapper springMapper;
|
||||
@MockitoBean
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager em;
|
||||
|
||||
private BookLoreUserEntity userEntity;
|
||||
private LibraryEntity library;
|
||||
private LibraryPathEntity libraryPath;
|
||||
private final Map<String, CategoryEntity> categories = new HashMap<>();
|
||||
private final Map<String, AuthorEntity> authors = new HashMap<>();
|
||||
|
||||
@TestConfiguration
|
||||
public static class TestConfig {
|
||||
@Bean("flyway")
|
||||
@Primary
|
||||
public Flyway flyway() {
|
||||
return mock(Flyway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public TaskCronService taskCronService() {
|
||||
return mock(TaskCronService.class);
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void seed() {
|
||||
facetService.clearCache();
|
||||
userEntity = BookLoreUserEntity.builder().username("reader").passwordHash("x").name("Reader").build();
|
||||
em.persist(userEntity);
|
||||
library = LibraryEntity.builder().name("Lib").icon("book").watch(false)
|
||||
.formatPriority(List.of(BookFileType.EPUB)).build();
|
||||
em.persist(library);
|
||||
libraryPath = LibraryPathEntity.builder().library(library).path("/p").build();
|
||||
em.persist(libraryPath);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(nonAdminUser());
|
||||
}
|
||||
|
||||
private BookLoreUser nonAdminUser() {
|
||||
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
|
||||
permissions.setAdmin(false);
|
||||
return BookLoreUser.builder()
|
||||
.id(userEntity.getId())
|
||||
.assignedLibraries(List.of(Library.builder().id(library.getId()).build()))
|
||||
.permissions(permissions)
|
||||
.build();
|
||||
}
|
||||
|
||||
private void book(String title, String genre, String authorName) {
|
||||
BookEntity bookEntity = BookEntity.builder()
|
||||
.library(library).libraryPath(libraryPath).addedOn(Instant.now()).deleted(false).build();
|
||||
em.persist(bookEntity);
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder().book(bookEntity).title(title).build();
|
||||
metadata.setCategories(java.util.Set.of(category(genre)));
|
||||
metadata.setAuthors(List.of(author(authorName)));
|
||||
em.persist(metadata);
|
||||
bookEntity.setMetadata(metadata);
|
||||
}
|
||||
|
||||
private CategoryEntity category(String name) {
|
||||
return categories.computeIfAbsent(name, n -> {
|
||||
CategoryEntity e = CategoryEntity.builder().name(n).build();
|
||||
em.persist(e);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
|
||||
private AuthorEntity author(String name) {
|
||||
return authors.computeIfAbsent(name, n -> {
|
||||
AuthorEntity e = AuthorEntity.builder().name(n).build();
|
||||
em.persist(e);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
|
||||
private FacetGroup group(FacetGroupsResponse response, String key) {
|
||||
return response.facets().stream()
|
||||
.filter(g -> g.metadata() != null && key.equals(g.metadata().key()))
|
||||
.findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
private Long count(FacetGroup group, String value) {
|
||||
Optional<FacetLink> link = group.links().stream().filter(l -> value.equals(l.value())).findFirst();
|
||||
return link.map(l -> l.properties().numberOfItems()).orElse(null);
|
||||
}
|
||||
|
||||
private FacetLink link(FacetGroup group, String value) {
|
||||
return group.links().stream()
|
||||
.filter(l -> value.equals(l.value()))
|
||||
.findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
@Test
|
||||
void countsDiscreteFacetsWithCounts() {
|
||||
book("A", "Horror", "Alice");
|
||||
book("B", "Romance", "Bob");
|
||||
em.flush();
|
||||
|
||||
FacetGroupsResponse response = facetService.getFacets(null, null, null);
|
||||
|
||||
assertThat(count(group(response, "genre"), "Horror")).isEqualTo(1);
|
||||
assertThat(count(group(response, "genre"), "Romance")).isEqualTo(1);
|
||||
assertThat(group(response, "author").links()).extracting(FacetLink::value).contains("Alice", "Bob");
|
||||
}
|
||||
|
||||
@Test
|
||||
void selectedFacetIsOmittedFromItsOwnCounts() {
|
||||
book("A", "Horror", "Alice");
|
||||
book("B", "Horror", "Alice");
|
||||
book("C", "Romance", "Bob");
|
||||
em.flush();
|
||||
|
||||
FacetGroupsResponse response = facetService.getFacets(List.of("genre:Horror"), null, null);
|
||||
|
||||
// genre omits itself: both Horror (2) and Romance (1) still appear with full counts.
|
||||
assertThat(count(group(response, "genre"), "Horror")).isEqualTo(2);
|
||||
assertThat(count(group(response, "genre"), "Romance")).isEqualTo(1);
|
||||
|
||||
// a different facet honors the genre:Horror filter: only Horror authors remain.
|
||||
assertThat(group(response, "author").links()).extracting(FacetLink::value).containsExactly("Alice");
|
||||
}
|
||||
|
||||
@Test
|
||||
void valuesAreOrderedByCountDescending() {
|
||||
book("A", "Horror", "Alice");
|
||||
book("B", "Horror", "Alice");
|
||||
book("C", "Romance", "Bob");
|
||||
em.flush();
|
||||
|
||||
List<String> genres = group(facetService.getFacets(null, null, null), "genre").links()
|
||||
.stream().map(FacetLink::value).toList();
|
||||
assertThat(genres).containsExactly("Horror", "Romance");
|
||||
}
|
||||
|
||||
@Test
|
||||
void linksCarryAddHrefAndCount() {
|
||||
book("A", "Horror", "Alice");
|
||||
em.flush();
|
||||
|
||||
FacetLink horror = link(group(facetService.getFacets(null, null, null), "genre"), "Horror");
|
||||
assertThat(horror.href()).isEqualTo("/api/v1/books/page?facet=genre%3AHorror");
|
||||
assertThat(horror.properties().numberOfItems()).isEqualTo(1);
|
||||
assertThat(horror.rel()).containsExactly("facet");
|
||||
}
|
||||
|
||||
@Test
|
||||
void responseIsCachedPerParameters() {
|
||||
book("A", "Horror", "Alice");
|
||||
em.flush();
|
||||
FacetGroupsResponse first = facetService.getFacets(null, null, null);
|
||||
FacetGroupsResponse second = facetService.getFacets(null, null, null);
|
||||
assertThat(first).isSameAs(second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void includesSortGroup() {
|
||||
book("A", "Horror", "Alice");
|
||||
em.flush();
|
||||
FacetGroup sort = group(facetService.getFacets(null, null, null), "sort");
|
||||
assertThat(sort.metadata().rel()).isEqualTo("sort");
|
||||
assertThat(sort.links()).extracting(FacetLink::value).contains("title", "-title");
|
||||
assertThat(sort.links()).allSatisfy(l -> assertThat(l.rel()).containsExactly("sort"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyFacetListBehavesLikeNullFacet() {
|
||||
book("A", "Horror", "Alice");
|
||||
book("B", "Romance", "Bob");
|
||||
em.flush();
|
||||
|
||||
FacetGroupsResponse withNull = facetService.getFacets(null, null, null);
|
||||
FacetGroupsResponse withEmpty = facetService.getFacets(List.of(), null, null);
|
||||
|
||||
assertThat(count(group(withEmpty, "genre"), "Horror")).isEqualTo(count(group(withNull, "genre"), "Horror"));
|
||||
assertThat(count(group(withEmpty, "genre"), "Romance")).isEqualTo(count(group(withNull, "genre"), "Romance"));
|
||||
assertThat(count(group(withEmpty, "genre"), "Horror")).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void multipleSelectionsFilterAcrossFacets() {
|
||||
book("A", "Horror", "Alice");
|
||||
book("B", "Horror", "Bob");
|
||||
book("C", "Romance", "Alice");
|
||||
em.flush();
|
||||
|
||||
FacetGroupsResponse response = facetService.getFacets(List.of("genre:Horror", "author:Alice"), null, null);
|
||||
|
||||
assertThat(count(group(response, "genre"), "Horror")).isEqualTo(1);
|
||||
assertThat(count(group(response, "genre"), "Romance")).isEqualTo(1);
|
||||
|
||||
assertThat(count(group(response, "author"), "Alice")).isEqualTo(1);
|
||||
assertThat(count(group(response, "author"), "Bob")).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void facetLogicCombinesSelectedValues() {
|
||||
book("A", "Horror", "Alice");
|
||||
book("B", "Romance", "Bob");
|
||||
book("C", "Fantasy", "Cara");
|
||||
em.flush();
|
||||
|
||||
List<String> genres = List.of("genre:Horror", "genre:Romance");
|
||||
|
||||
assertThat(group(facetService.getFacets(genres, "or", null), "author").links())
|
||||
.extracting(FacetLink::value).containsExactlyInAnyOrder("Alice", "Bob");
|
||||
|
||||
assertThat(group(facetService.getFacets(genres, "and", null), "author").links()).isEmpty();
|
||||
|
||||
assertThat(group(facetService.getFacets(genres, "not", null), "author").links())
|
||||
.extracting(FacetLink::value).containsExactly("Cara");
|
||||
}
|
||||
|
||||
@Test
|
||||
void truncatesValuesAtMax() {
|
||||
for (int i = 0; i < 101; i++) {
|
||||
book("T" + i, "Genre" + i, "Author" + i);
|
||||
}
|
||||
em.flush();
|
||||
|
||||
FacetGroupsResponse response = facetService.getFacets(null, null, null);
|
||||
|
||||
assertThat(group(response, "genre").links()).hasSize(100);
|
||||
assertThat(group(response, "author").links()).hasSize(100);
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeFacetIsMarkedSelfWithCurrentPageHref() {
|
||||
book("A", "Horror", "Alice");
|
||||
book("B", "Romance", "Bob");
|
||||
em.flush();
|
||||
|
||||
FacetGroup genre = group(facetService.getFacets(List.of("genre:Horror"), null, null), "genre");
|
||||
FacetLink horror = link(genre, "Horror");
|
||||
FacetLink romance = link(genre, "Romance");
|
||||
|
||||
assertThat(horror.rel()).containsExactly("self", "facet");
|
||||
assertThat(horror.href()).isEqualTo("/api/v1/books/page?facet=genre%3AHorror");
|
||||
|
||||
assertThat(romance.rel()).containsExactly("facet");
|
||||
assertThat(romance.href()).isEqualTo("/api/v1/books/page?facet=genre%3AHorror&facet=genre%3ARomance");
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeFacetSelfHrefKeepsAllSelections() {
|
||||
book("A", "Horror", "Alice");
|
||||
em.flush();
|
||||
|
||||
FacetGroup genre = group(facetService.getFacets(List.of("genre:Horror", "author:Alice"), null, null), "genre");
|
||||
FacetLink horror = link(genre, "Horror");
|
||||
|
||||
assertThat(horror.rel()).containsExactly("self", "facet");
|
||||
assertThat(horror.href()).isEqualTo("/api/v1/books/page?facet=genre%3AHorror&facet=author%3AAlice");
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeFacetMatchIsCaseInsensitive() {
|
||||
book("A", "Horror", "Alice");
|
||||
em.flush();
|
||||
|
||||
FacetGroup genre = group(facetService.getFacets(List.of("genre:horror"), null, null), "genre");
|
||||
FacetLink horror = link(genre, "Horror");
|
||||
|
||||
assertThat(horror.rel()).contains("self");
|
||||
}
|
||||
|
||||
@Test
|
||||
void responseCarriesTopLevelSelfLink() {
|
||||
book("A", "Horror", "Alice");
|
||||
em.flush();
|
||||
|
||||
Link bare = facetService.getFacets(null, null, null).links().getFirst();
|
||||
assertThat(bare.rel()).containsExactly("self");
|
||||
assertThat(bare.href()).isEqualTo("/api/v1/books/facets");
|
||||
assertThat(bare.type()).isEqualTo(Link.JSON_TYPE);
|
||||
|
||||
Link filtered = facetService.getFacets(List.of("genre:Horror"), null, "dune").links().getFirst();
|
||||
assertThat(filtered.rel()).containsExactly("self");
|
||||
assertThat(filtered.href()).isEqualTo("/api/v1/books/facets?facet=genre%3AHorror&query=dune");
|
||||
}
|
||||
|
||||
// Serializes through the Spring-managed Jackson 3 mapper, the same one the HTTP
|
||||
// layer uses, so a mapper/annotation mismatch can't slip through unit tests again.
|
||||
@Test
|
||||
void springMapperSerializesSingleRelAsString() {
|
||||
book("A", "Horror", "Alice");
|
||||
em.flush();
|
||||
|
||||
String json = springMapper.writeValueAsString(facetService.getFacets(List.of("genre:Horror"), null, null));
|
||||
|
||||
assertThat(json).contains("\"rel\":\"self\"");
|
||||
assertThat(json).contains("\"rel\":[\"self\",\"facet\"]");
|
||||
assertThat(json).doesNotContain("\"rel\":[\"self\"]");
|
||||
assertThat(json).doesNotContain("\"rel\":[\"facet\"]");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user