//! The catalog search builder. //! //! [`SearchQuery`] covers the documented thunder search parameters and turns //! them into a query string with [`SearchQuery::to_params`], which is also //! where out-of-range values are rejected before any request is made. use crate::Error; use crate::ids::{FormatId, TitleId}; use crate::models::{MediaKind, SortBy}; /// The Libby UI's page size. pub const DEFAULT_PER_PAGE: u32 = 24; /// The largest page size this client will ask for. pub const MAX_PER_PAGE: u32 = 100; /// A catalog search against one library (`GET /libraries/{key}/media`). /// /// ``` /// use libby::{SearchQuery, models::{MediaKind, SortBy}}; /// /// let query = SearchQuery::new() /// .text("dune") /// .media_type(MediaKind::Audiobook) /// .available_only(true) /// .sort(SortBy::NewlyAdded) /// .page(2); /// assert!(query.to_params().is_ok()); /// ``` #[derive(Debug, Clone, PartialEq)] pub struct SearchQuery { text: Option, title: Option, creator: Option, identifier: Option, media_types: Vec, formats: Vec, subjects: Vec, bisac_code: Option, language: Option, available_only: bool, prerelease_only: bool, title_ids: Vec, sort: Option, page: u32, per_page: u32, include_facets: bool, } impl Default for SearchQuery { fn default() -> Self { Self { text: None, title: None, creator: None, identifier: None, media_types: Vec::new(), formats: Vec::new(), subjects: Vec::new(), bisac_code: None, language: None, available_only: false, prerelease_only: false, title_ids: Vec::new(), sort: None, page: 1, per_page: DEFAULT_PER_PAGE, include_facets: true, } } } impl SearchQuery { /// An empty query: everything, page 1, 24 per page, facets included. #[must_use] pub fn new() -> Self { Self::default() } /// Free-text search (`query`). #[must_use] pub fn text(mut self, text: impl Into) -> Self { self.text = Some(text.into()); self } /// Title field search (`title`). #[must_use] pub fn title(mut self, title: impl Into) -> Self { self.title = Some(title.into()); self } /// Creator field search (`creator`). #[must_use] pub fn creator(mut self, creator: impl Into) -> Self { self.creator = Some(creator.into()); self } /// Identifier search, e.g. an ISBN (`identifier`). #[must_use] pub fn identifier(mut self, identifier: impl Into) -> Self { self.identifier = Some(identifier.into()); self } /// Restrict to a media kind (`mediaTypes`); call repeatedly for several. #[must_use] pub fn media_type(mut self, kind: MediaKind) -> Self { if !self.media_types.contains(&kind) { self.media_types.push(kind); } self } /// Restrict to a format (`format`); call repeatedly for several. #[must_use] pub fn format(mut self, format: FormatId) -> Self { if !self.formats.contains(&format) { self.formats.push(format); } self } /// Restrict to a subject id from the facets (`subject`, repeatable). #[must_use] pub fn subject(mut self, subject: impl Into) -> Self { self.subjects.push(subject.into()); self } /// Restrict to a BISAC code (`bisacCode`). #[must_use] pub fn bisac_code(mut self, code: impl Into) -> Self { self.bisac_code = Some(code.into()); self } /// Restrict to a language id such as `"en"` (`language`). #[must_use] pub fn language(mut self, language: impl Into) -> Self { self.language = Some(language.into()); self } /// Only titles with a copy on the shelf (`showOnlyAvailable`). #[must_use] pub fn available_only(mut self, yes: bool) -> Self { self.available_only = yes; self } /// Only titles not released yet (`showOnlyPrerelease`). #[must_use] pub fn prerelease_only(mut self, yes: bool) -> Self { self.prerelease_only = yes; self } /// Restrict to specific titles (`titleIds`). #[must_use] pub fn title_ids(mut self, ids: impl IntoIterator) -> Self { self.title_ids.extend(ids); self } /// Sort order (`sortBy`); the server's default when unset. #[must_use] pub fn sort(mut self, sort: SortBy) -> Self { self.sort = Some(sort); self } /// 1-based page number (`page`). #[must_use] pub fn page(mut self, page: u32) -> Self { self.page = page; self } /// Page size (`perPage`), 1..=100. #[must_use] pub fn per_page(mut self, per_page: u32) -> Self { self.per_page = per_page; self } /// Whether to ask for facets (`includeFacets`). #[must_use] pub fn include_facets(mut self, yes: bool) -> Self { self.include_facets = yes; self } /// The current page number. #[must_use] pub fn current_page(&self) -> u32 { self.page } /// The query string pairs, in a stable order. /// /// # Errors /// /// [`Error::InvalidInput`] for page 0 or a page size outside 1..=100. pub fn to_params(&self) -> crate::Result> { if self.page == 0 { return Err(Error::InvalidInput("search pages start at 1".into())); } if !(1..=MAX_PER_PAGE).contains(&self.per_page) { return Err(Error::InvalidInput(format!( "page size {} is outside 1..={MAX_PER_PAGE}", self.per_page ))); } let mut params = Vec::new(); let mut text = |key, value: &Option| { if let Some(value) = value.as_deref().map(str::trim).filter(|v| !v.is_empty()) { params.push((key, value.to_owned())); } }; text("query", &self.text); text("title", &self.title); text("creator", &self.creator); text("identifier", &self.identifier); text("bisacCode", &self.bisac_code); text("language", &self.language); let csv = |items: Vec<&str>| items.join(","); if !self.media_types.is_empty() { params.push(( "mediaTypes", csv(self.media_types.iter().map(MediaKind::as_str).collect()), )); } if !self.formats.is_empty() { params.push(( "format", csv(self.formats.iter().map(FormatId::as_str).collect()), )); } for subject in &self.subjects { params.push(("subject", subject.clone())); } if !self.title_ids.is_empty() { params.push(( "titleIds", csv(self.title_ids.iter().map(TitleId::as_str).collect()), )); } if self.available_only { params.push(("showOnlyAvailable", "true".to_owned())); } if self.prerelease_only { params.push(("showOnlyPrerelease", "true".to_owned())); } if let Some(sort) = &self.sort { params.push(("sortBy", sort.as_str().to_owned())); } params.push(("page", self.page.to_string())); params.push(("perPage", self.per_page.to_string())); if self.include_facets { params.push(("includeFacets", "true".to_owned())); } Ok(params) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use pretty_assertions::assert_eq; use super::*; #[test] fn defaults() { assert_eq!( SearchQuery::new().to_params().unwrap(), [ ("page", "1".to_owned()), ("perPage", "24".to_owned()), ("includeFacets", "true".to_owned()) ] ); } #[test] fn every_parameter() { let params = SearchQuery::new() .text(" dune ") .title("Dune") .creator("Herbert") .identifier("9781427201447") .media_type(MediaKind::Audiobook) .media_type(MediaKind::Ebook) .media_type(MediaKind::Audiobook) .format(FormatId::new("ebook-epub-open")) .subject("26") .subject("80") .bisac_code("FIC028030") .language("en") .available_only(true) .prerelease_only(true) .title_ids([TitleId::new("1"), TitleId::new("2")]) .sort(SortBy::MostPopularSite) .page(3) .per_page(50) .include_facets(false) .to_params() .unwrap(); let expected: Vec<(&str, String)> = [ ("query", "dune"), ("title", "Dune"), ("creator", "Herbert"), ("identifier", "9781427201447"), ("bisacCode", "FIC028030"), ("language", "en"), ("mediaTypes", "audiobook,ebook"), ("format", "ebook-epub-open"), ("subject", "26"), ("subject", "80"), ("titleIds", "1,2"), ("showOnlyAvailable", "true"), ("showOnlyPrerelease", "true"), ("sortBy", "mostpopular-site"), ("page", "3"), ("perPage", "50"), ] .into_iter() .map(|(k, v)| (k, v.to_owned())) .collect(); assert_eq!(params, expected); } #[test] fn rejects_bad_paging() { assert!(SearchQuery::new().page(0).to_params().is_err()); assert!(SearchQuery::new().per_page(0).to_params().is_err()); assert!(SearchQuery::new().per_page(101).to_params().is_err()); } }