paginated authors
This commit is contained in:
parent
352d4e0a7a
commit
ead3672570
@ -34,7 +34,7 @@ impl Calibre {
|
||||
&self,
|
||||
limit: u64,
|
||||
cursor: Option<&str>,
|
||||
sort_order: SortOrder,
|
||||
sort_order: &SortOrder,
|
||||
) -> Result<Vec<Author>, DataStoreError> {
|
||||
let conn = self.pool.get()?;
|
||||
Author::multiple(&conn, limit, cursor, sort_order)
|
||||
@ -80,6 +80,16 @@ impl Calibre {
|
||||
let conn = self.pool.get()?;
|
||||
Series::book_series(&conn, id)
|
||||
}
|
||||
|
||||
pub fn has_previous_authors(&self, author_sort: &str) -> Result<bool, DataStoreError> {
|
||||
let conn = self.pool.get()?;
|
||||
Author::has_previous_authors(&conn, author_sort)
|
||||
}
|
||||
|
||||
pub fn has_more_authors(&self, author_sort: &str) -> Result<bool, DataStoreError> {
|
||||
let conn = self.pool.get()?;
|
||||
Author::has_more_authors(&conn, author_sort)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@ -100,7 +110,7 @@ mod tests {
|
||||
#[test]
|
||||
fn authors() {
|
||||
let c = init_calibre();
|
||||
let authors = c.authors(10, None, SortOrder::ASC).unwrap();
|
||||
let authors = c.authors(10, None, &SortOrder::ASC).unwrap();
|
||||
assert_eq!(authors.len(), 3);
|
||||
}
|
||||
|
||||
@ -114,24 +124,24 @@ mod tests {
|
||||
#[test]
|
||||
fn pagination() {
|
||||
let c = init_calibre();
|
||||
let authors = c.authors(1, None, SortOrder::ASC).unwrap();
|
||||
let authors = c.authors(1, None, &SortOrder::ASC).unwrap();
|
||||
assert_eq!(authors.len(), 1);
|
||||
assert_eq!(authors[0].name, "Kevin R. Grazier");
|
||||
|
||||
let authors = c
|
||||
.authors(1, Some(&authors[0].sort), SortOrder::ASC)
|
||||
.authors(1, Some(&authors[0].sort), &SortOrder::ASC)
|
||||
.unwrap();
|
||||
assert_eq!(authors.len(), 1);
|
||||
assert_eq!(authors[0].name, "Terry Pratchett");
|
||||
|
||||
let authors = c
|
||||
.authors(1, Some(&authors[0].sort), SortOrder::ASC)
|
||||
.authors(1, Some(&authors[0].sort), &SortOrder::ASC)
|
||||
.unwrap();
|
||||
assert_eq!(authors.len(), 1);
|
||||
assert_eq!(authors[0].name, "Edward Noyes Westcott");
|
||||
|
||||
let authors = c
|
||||
.authors(1, Some(&authors[0].sort), SortOrder::DESC)
|
||||
.authors(1, Some(&authors[0].sort), &SortOrder::DESC)
|
||||
.unwrap();
|
||||
assert_eq!(authors.len(), 1);
|
||||
assert_eq!(authors[0].name, "Terry Pratchett");
|
||||
|
@ -26,9 +26,9 @@ impl Author {
|
||||
conn: &Connection,
|
||||
limit: u64,
|
||||
cursor: Option<&str>,
|
||||
sort_order: SortOrder,
|
||||
sort_order: &SortOrder,
|
||||
) -> Result<Vec<Self>, DataStoreError> {
|
||||
let pagination = Pagination::new("sort", cursor, limit, sort_order);
|
||||
let pagination = Pagination::new("sort", cursor, limit, *sort_order);
|
||||
pagination.paginate(
|
||||
conn,
|
||||
"SELECT id, name, sort FROM authors",
|
||||
@ -46,4 +46,25 @@ impl Author {
|
||||
let params = named_params! { ":id": id };
|
||||
Ok(stmt.query_row(params, Self::from_row)?)
|
||||
}
|
||||
|
||||
pub fn has_previous_authors(
|
||||
conn: &Connection,
|
||||
sort_name: &str,
|
||||
) -> Result<bool, DataStoreError> {
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT Count(1) FROM authors WHERE sort < (:sort_name) ORDER BY sort DESC")?;
|
||||
let params = named_params! { ":sort_name": sort_name };
|
||||
let count: u64 = stmt.query_row(params, |x| x.get(0))?;
|
||||
|
||||
Ok(count > 0)
|
||||
}
|
||||
|
||||
pub fn has_more_authors(conn: &Connection, sort_name: &str) -> Result<bool, DataStoreError> {
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT Count(1) FROM authors WHERE sort > (:sort_name) ORDER BY sort ASC")?;
|
||||
let params = named_params! { ":sort_name": sort_name };
|
||||
let count: u64 = stmt.query_row(params, |x| x.get(0))?;
|
||||
|
||||
Ok(count > 0)
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,9 @@
|
||||
use rusqlite::{Connection, Row, ToSql};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::error::DataStoreError;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Deserialize, Serialize)]
|
||||
pub enum SortOrder {
|
||||
ASC,
|
||||
DESC,
|
||||
@ -53,10 +54,17 @@ impl<'a> Pagination<'a> {
|
||||
};
|
||||
|
||||
let sort_col = self.sort_col;
|
||||
// otherwise paginated statements with join will fail
|
||||
let sort_col_wrapped = if let Some(index) = sort_col.find('.') {
|
||||
let right_part = &sort_col[index..];
|
||||
"t".to_owned() + right_part
|
||||
} else {
|
||||
sort_col.to_owned()
|
||||
};
|
||||
let sort_order = &self.sort_order;
|
||||
// DANGER: vulnerable to SQL injection if statement or sort_col variable is influenced by user input
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"{statement} {where_sql} {sort_col} {comparison} (:cursor) ORDER BY {sort_col} {sort_order:?} LIMIT (:limit)"
|
||||
"SELECT * FROM ({statement} {where_sql} {sort_col} {comparison} (:cursor) ORDER BY {sort_col} {sort_order:?} LIMIT (:limit)) AS t ORDER BY {sort_col_wrapped} ASC"
|
||||
))?;
|
||||
let params = [
|
||||
&[
|
||||
|
@ -1,10 +1,34 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use poem::{handler, web::Data};
|
||||
use calibre_db::data::pagination::SortOrder;
|
||||
use poem::{
|
||||
handler,
|
||||
web::{Data, Html, Path},
|
||||
};
|
||||
|
||||
use crate::app_state::AppState;
|
||||
use crate::{app_state::AppState, handlers::paginated};
|
||||
|
||||
#[handler]
|
||||
pub async fn handler(state: Data<&Arc<AppState>>) -> Result<String, poem::Error> {
|
||||
Ok("authors".to_string())
|
||||
pub async fn handler_init(state: Data<&Arc<AppState>>) -> Result<Html<String>, poem::Error> {
|
||||
paginated::render(
|
||||
"authors",
|
||||
|| state.calibre.authors(25, None, &SortOrder::ASC),
|
||||
|author| author.sort.clone(),
|
||||
|cursor| state.calibre.has_previous_authors(cursor),
|
||||
|cursor| state.calibre.has_more_authors(cursor),
|
||||
)
|
||||
}
|
||||
|
||||
#[handler]
|
||||
pub async fn handler(
|
||||
Path((cursor, sort_order)): Path<(String, SortOrder)>,
|
||||
state: Data<&Arc<AppState>>,
|
||||
) -> Result<Html<String>, poem::Error> {
|
||||
paginated::render(
|
||||
"authors",
|
||||
|| state.calibre.authors(25, Some(&cursor), &sort_order),
|
||||
|author| author.sort.clone(),
|
||||
|cursor| state.calibre.has_previous_authors(cursor),
|
||||
|cursor| state.calibre.has_more_authors(cursor),
|
||||
)
|
||||
}
|
||||
|
46
rusty-library/src/handlers/paginated.rs
Normal file
46
rusty-library/src/handlers/paginated.rs
Normal file
@ -0,0 +1,46 @@
|
||||
use calibre_db::data::error::DataStoreError;
|
||||
use poem::{error::InternalServerError, web::Html};
|
||||
use serde::Serialize;
|
||||
use tera::Context;
|
||||
|
||||
use crate::templates::TEMPLATES;
|
||||
|
||||
use super::error::SqliteError;
|
||||
|
||||
pub fn render<T: Serialize, F, S, P, M>(
|
||||
template: &str,
|
||||
fetcher: F,
|
||||
sort_field: S,
|
||||
has_previous: P,
|
||||
has_more: M,
|
||||
) -> Result<Html<String>, poem::Error>
|
||||
where
|
||||
F: Fn() -> Result<Vec<T>, DataStoreError>,
|
||||
S: Fn(&T) -> String,
|
||||
P: Fn(&str) -> Result<bool, DataStoreError>,
|
||||
M: Fn(&str) -> Result<bool, DataStoreError>,
|
||||
{
|
||||
let items = fetcher().map_err(SqliteError)?;
|
||||
|
||||
let mut context = Context::new();
|
||||
|
||||
// fails already in the sql query if there is nothing returned
|
||||
let first_item = items.first().unwrap();
|
||||
let last_item = items.last().unwrap();
|
||||
|
||||
let (backward_cursor, forward_cursor) = (sort_field(first_item), sort_field(last_item));
|
||||
|
||||
let has_previous = has_previous(&backward_cursor).map_err(SqliteError)?;
|
||||
let has_more = has_more(&forward_cursor).map_err(SqliteError)?;
|
||||
|
||||
context.insert("has_previous", &has_previous);
|
||||
context.insert("has_more", &has_more);
|
||||
context.insert("backward_cursor", &backward_cursor);
|
||||
context.insert("forward_cursor", &forward_cursor);
|
||||
context.insert("nav", template);
|
||||
context.insert(template, &items);
|
||||
TEMPLATES
|
||||
.render(template, &context)
|
||||
.map_err(InternalServerError)
|
||||
.map(Html)
|
||||
}
|
@ -13,13 +13,15 @@ use crate::{
|
||||
|
||||
#[handler]
|
||||
pub async fn handler(state: Data<&Arc<AppState>>) -> Result<Html<String>, poem::Error> {
|
||||
let recent_books = state.calibre.recent_books(50).map_err(SqliteError)?;
|
||||
let recent_books = state.calibre.recent_books(25).map_err(SqliteError)?;
|
||||
let recent_books = recent_books
|
||||
.iter()
|
||||
.filter_map(|x| Book::full_book(x, &state))
|
||||
.collect::<Vec<Book>>();
|
||||
|
||||
let mut context = Context::new();
|
||||
context.insert("title", "Recent Books");
|
||||
context.insert("nav", "recent");
|
||||
context.insert("books", &recent_books);
|
||||
TEMPLATES
|
||||
.render("recents", &context)
|
||||
|
@ -23,6 +23,7 @@ mod handlers {
|
||||
pub mod cover;
|
||||
pub mod download;
|
||||
pub mod error;
|
||||
pub mod paginated;
|
||||
pub mod recents;
|
||||
pub mod series;
|
||||
}
|
||||
@ -48,7 +49,11 @@ async fn main() -> Result<(), std::io::Error> {
|
||||
let app = Route::new()
|
||||
.at("/", get(handlers::recents::handler))
|
||||
.at("/books", get(handlers::books::handler))
|
||||
.at("/authors", get(handlers::authors::handler))
|
||||
.at("/authors", get(handlers::authors::handler_init))
|
||||
.at(
|
||||
"/authors/:cursor/:sort_order",
|
||||
get(handlers::authors::handler),
|
||||
)
|
||||
.at("/series", get(handlers::series::handler))
|
||||
.at("/cover/:id", get(handlers::cover::handler))
|
||||
.at("/book/:id/:format", get(handlers::download::handler))
|
||||
|
@ -6,6 +6,7 @@ pub static TEMPLATES: Lazy<Tera> = Lazy::new(|| {
|
||||
tera.add_raw_templates(vec![
|
||||
("base", include_str!("../templates/base.html")),
|
||||
("book_card", include_str!("../templates/book_card.html")),
|
||||
("authors", include_str!("../templates/authors.html")),
|
||||
("recents", include_str!("../templates/recents.html")),
|
||||
])
|
||||
.expect("failed to parse tera templates");
|
||||
|
@ -3,6 +3,21 @@
|
||||
overflow: scroll;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
header.fixed {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1000;
|
||||
background: var(--pico-background-color)
|
||||
}
|
||||
|
||||
nav ul li {
|
||||
padding-top: 0rem;
|
||||
padding-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.nav-active {
|
||||
border-bottom: solid var(--pico-primary-underline);
|
||||
}
|
||||
|
||||
.book-card hgroup {
|
||||
margin-bottom: 0;
|
||||
|
19
rusty-library/templates/authors.html
Normal file
19
rusty-library/templates/authors.html
Normal file
@ -0,0 +1,19 @@
|
||||
{% extends "base" %}
|
||||
{% block title %}
|
||||
{% if has_previous %}
|
||||
<a href="/authors/{{ backward_cursor }}/DESC">← back</a>
|
||||
{% endif %}
|
||||
{% if has_previous and has_more %}|{% endif%}
|
||||
|
||||
{% if has_more %}
|
||||
<a href="/authors/{{ forward_cursor }}/ASC">more →</a>
|
||||
{% endif %}
|
||||
{% endblock title %}
|
||||
|
||||
{% block content %}
|
||||
<div class="grid-container">
|
||||
{% for author in authors %}
|
||||
<article>{{ author.name }}</article>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endblock content %}
|
@ -9,18 +9,20 @@
|
||||
<title>Rusty Library</title>
|
||||
</head>
|
||||
<body>
|
||||
<main class="container">
|
||||
<header class="container fixed">
|
||||
<nav>
|
||||
<ul>
|
||||
<li><strong>Library</strong></li>
|
||||
<li>{% block title %}<strong>{{ title }}</strong>{% endblock title %}</li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="/">Recent</a></li>
|
||||
<li><a href="/authors">Authors</a></li>
|
||||
<li><a href="/books">Books</a></li>
|
||||
<li><a href="/series">Series</a></li>
|
||||
<li {% if nav == "recent" %}class = "nav-active"{% endif %}><a href="/">Recent</a></li>
|
||||
<li {% if nav == "authors" %}class = "nav-active"{% endif %}><a href="/authors">Authors</a></li>
|
||||
<li {% if nav == "books" %}class = "nav-active"{% endif %}><a href="/books">Books</a></li>
|
||||
<li {% if nav == "series" %}class = "nav-active"{% endif %}><a href="/series">Series</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
</header>
|
||||
<main class="container">
|
||||
{% block content %}{% endblock content %}
|
||||
</main>
|
||||
</body>
|
||||
|
@ -1,6 +1,5 @@
|
||||
{% extends "base" %}
|
||||
{% block content %}
|
||||
<h1>Recent Books</h1>
|
||||
<div class="grid-container">
|
||||
{% for book in books %}
|
||||
{% include "book_card" %}
|
||||
|
Loading…
Reference in New Issue
Block a user