lib/contexts/
book.rs

1//! Defines the context for [`Book`] data.
2
3use serde::Serialize;
4
5use crate::models::book::{Book, BookMetadata};
6use crate::strings;
7
8/// A struct representing a [`Book`] within a template context.
9///
10/// See [`Book`] for undocumented fields.
11#[derive(Debug, Serialize)]
12pub struct BookContext<'a> {
13    #[allow(missing_docs)]
14    pub title: &'a str,
15    #[allow(missing_docs)]
16    pub author: &'a String,
17    #[allow(missing_docs)]
18    pub metadata: &'a BookMetadata,
19
20    /// A [`Book`]s slugified strings.
21    pub slugs: BookSlugs,
22}
23
24impl<'a> From<&'a Book> for BookContext<'a> {
25    fn from(book: &'a Book) -> Self {
26        let last_opened = if let Some(date) = &book.metadata.last_opened {
27            strings::to_slug_date(date)
28        } else {
29            String::new()
30        };
31
32        Self {
33            title: &book.title,
34            author: &book.author,
35            metadata: &book.metadata,
36            slugs: BookSlugs {
37                title: strings::to_slug(&book.title, true),
38                author: strings::to_slug(&book.author, true),
39                metadata: BookMetadataSlugs { last_opened },
40            },
41        }
42    }
43}
44
45/// A struct representing a [`Book`]'s slugified strings.
46#[derive(Debug, Default, Clone, Serialize)]
47pub struct BookSlugs {
48    #[allow(missing_docs)]
49    pub title: String,
50    #[allow(missing_docs)]
51    pub author: String,
52    #[allow(missing_docs)]
53    pub metadata: BookMetadataSlugs,
54}
55
56/// A struct representing an [`BookMetadata`]'s slugified strings.
57///
58/// See [`BookMetadata`] for undocumented fields.
59#[derive(Debug, Default, Clone, Serialize)]
60pub struct BookMetadataSlugs {
61    #[allow(missing_docs)]
62    pub last_opened: String,
63}