paginated authors
This commit is contained in:
parent
352d4e0a7a
commit
ead3672570
@ -34,7 +34,7 @@ impl Calibre {
|
|||||||
&self,
|
&self,
|
||||||
limit: u64,
|
limit: u64,
|
||||||
cursor: Option<&str>,
|
cursor: Option<&str>,
|
||||||
sort_order: SortOrder,
|
sort_order: &SortOrder,
|
||||||
) -> Result<Vec<Author>, DataStoreError> {
|
) -> Result<Vec<Author>, DataStoreError> {
|
||||||
let conn = self.pool.get()?;
|
let conn = self.pool.get()?;
|
||||||
Author::multiple(&conn, limit, cursor, sort_order)
|
Author::multiple(&conn, limit, cursor, sort_order)
|
||||||
@ -80,6 +80,16 @@ impl Calibre {
|
|||||||
let conn = self.pool.get()?;
|
let conn = self.pool.get()?;
|
||||||
Series::book_series(&conn, id)
|
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)]
|
#[cfg(test)]
|
||||||
@ -100,7 +110,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn authors() {
|
fn authors() {
|
||||||
let c = init_calibre();
|
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);
|
assert_eq!(authors.len(), 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -114,24 +124,24 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn pagination() {
|
fn pagination() {
|
||||||
let c = init_calibre();
|
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.len(), 1);
|
||||||
assert_eq!(authors[0].name, "Kevin R. Grazier");
|
assert_eq!(authors[0].name, "Kevin R. Grazier");
|
||||||
|
|
||||||
let authors = c
|
let authors = c
|
||||||
.authors(1, Some(&authors[0].sort), SortOrder::ASC)
|
.authors(1, Some(&authors[0].sort), &SortOrder::ASC)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(authors.len(), 1);
|
assert_eq!(authors.len(), 1);
|
||||||
assert_eq!(authors[0].name, "Terry Pratchett");
|
assert_eq!(authors[0].name, "Terry Pratchett");
|
||||||
|
|
||||||
let authors = c
|
let authors = c
|
||||||
.authors(1, Some(&authors[0].sort), SortOrder::ASC)
|
.authors(1, Some(&authors[0].sort), &SortOrder::ASC)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(authors.len(), 1);
|
assert_eq!(authors.len(), 1);
|
||||||
assert_eq!(authors[0].name, "Edward Noyes Westcott");
|
assert_eq!(authors[0].name, "Edward Noyes Westcott");
|
||||||
|
|
||||||
let authors = c
|
let authors = c
|
||||||
.authors(1, Some(&authors[0].sort), SortOrder::DESC)
|
.authors(1, Some(&authors[0].sort), &SortOrder::DESC)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(authors.len(), 1);
|
assert_eq!(authors.len(), 1);
|
||||||
assert_eq!(authors[0].name, "Terry Pratchett");
|
assert_eq!(authors[0].name, "Terry Pratchett");
|
||||||
|
@ -26,9 +26,9 @@ impl Author {
|
|||||||
conn: &Connection,
|
conn: &Connection,
|
||||||
limit: u64,
|
limit: u64,
|
||||||
cursor: Option<&str>,
|
cursor: Option<&str>,
|
||||||
sort_order: SortOrder,
|
sort_order: &SortOrder,
|
||||||
) -> Result<Vec<Self>, DataStoreError> {
|
) -> Result<Vec<Self>, DataStoreError> {
|
||||||
let pagination = Pagination::new("sort", cursor, limit, sort_order);
|
let pagination = Pagination::new("sort", cursor, limit, *sort_order);
|
||||||
pagination.paginate(
|
pagination.paginate(
|
||||||
conn,
|
conn,
|
||||||
"SELECT id, name, sort FROM authors",
|
"SELECT id, name, sort FROM authors",
|
||||||
@ -46,4 +46,25 @@ impl Author {
|
|||||||
let params = named_params! { ":id": id };
|
let params = named_params! { ":id": id };
|
||||||
Ok(stmt.query_row(params, Self::from_row)?)
|
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 rusqlite::{Connection, Row, ToSql};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use super::error::DataStoreError;
|
use super::error::DataStoreError;
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Deserialize, Serialize)]
|
||||||
pub enum SortOrder {
|
pub enum SortOrder {
|
||||||
ASC,
|
ASC,
|
||||||
DESC,
|
DESC,
|
||||||
@ -53,10 +54,17 @@ impl<'a> Pagination<'a> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let sort_col = self.sort_col;
|
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;
|
let sort_order = &self.sort_order;
|
||||||
// DANGER: vulnerable to SQL injection if statement or sort_col variable is influenced by user input
|
// DANGER: vulnerable to SQL injection if statement or sort_col variable is influenced by user input
|
||||||
let mut stmt = conn.prepare(&format!(
|
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 = [
|
let params = [
|
||||||
&[
|
&[
|
||||||
|
@ -1,10 +1,34 @@
|
|||||||
use std::sync::Arc;
|
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]
|
#[handler]
|
||||||
pub async fn handler(state: Data<&Arc<AppState>>) -> Result<String, poem::Error> {
|
pub async fn handler_init(state: Data<&Arc<AppState>>) -> Result<Html<String>, poem::Error> {
|
||||||
Ok("authors".to_string())
|
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]
|
#[handler]
|
||||||
pub async fn handler(state: Data<&Arc<AppState>>) -> Result<Html<String>, poem::Error> {
|
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
|
let recent_books = recent_books
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|x| Book::full_book(x, &state))
|
.filter_map(|x| Book::full_book(x, &state))
|
||||||
.collect::<Vec<Book>>();
|
.collect::<Vec<Book>>();
|
||||||
|
|
||||||
let mut context = Context::new();
|
let mut context = Context::new();
|
||||||
|
context.insert("title", "Recent Books");
|
||||||
|
context.insert("nav", "recent");
|
||||||
context.insert("books", &recent_books);
|
context.insert("books", &recent_books);
|
||||||
TEMPLATES
|
TEMPLATES
|
||||||
.render("recents", &context)
|
.render("recents", &context)
|
||||||
|
@ -23,6 +23,7 @@ mod handlers {
|
|||||||
pub mod cover;
|
pub mod cover;
|
||||||
pub mod download;
|
pub mod download;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
pub mod paginated;
|
||||||
pub mod recents;
|
pub mod recents;
|
||||||
pub mod series;
|
pub mod series;
|
||||||
}
|
}
|
||||||
@ -48,7 +49,11 @@ async fn main() -> Result<(), std::io::Error> {
|
|||||||
let app = Route::new()
|
let app = Route::new()
|
||||||
.at("/", get(handlers::recents::handler))
|
.at("/", get(handlers::recents::handler))
|
||||||
.at("/books", get(handlers::books::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("/series", get(handlers::series::handler))
|
||||||
.at("/cover/:id", get(handlers::cover::handler))
|
.at("/cover/:id", get(handlers::cover::handler))
|
||||||
.at("/book/:id/:format", get(handlers::download::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![
|
tera.add_raw_templates(vec![
|
||||||
("base", include_str!("../templates/base.html")),
|
("base", include_str!("../templates/base.html")),
|
||||||
("book_card", include_str!("../templates/book_card.html")),
|
("book_card", include_str!("../templates/book_card.html")),
|
||||||
|
("authors", include_str!("../templates/authors.html")),
|
||||||
("recents", include_str!("../templates/recents.html")),
|
("recents", include_str!("../templates/recents.html")),
|
||||||
])
|
])
|
||||||
.expect("failed to parse tera templates");
|
.expect("failed to parse tera templates");
|
||||||
|
@ -3,6 +3,21 @@
|
|||||||
overflow: scroll;
|
overflow: scroll;
|
||||||
text-overflow: ellipsis;
|
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 {
|
.book-card hgroup {
|
||||||
margin-bottom: 0;
|
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>
|
<title>Rusty Library</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="container">
|
<header class="container fixed">
|
||||||
<nav>
|
<nav>
|
||||||
<ul>
|
<ul>
|
||||||
<li><strong>Library</strong></li>
|
<li>{% block title %}<strong>{{ title }}</strong>{% endblock title %}</li>
|
||||||
</ul>
|
</ul>
|
||||||
<ul>
|
<ul>
|
||||||
<li><a href="/">Recent</a></li>
|
<li {% if nav == "recent" %}class = "nav-active"{% endif %}><a href="/">Recent</a></li>
|
||||||
<li><a href="/authors">Authors</a></li>
|
<li {% if nav == "authors" %}class = "nav-active"{% endif %}><a href="/authors">Authors</a></li>
|
||||||
<li><a href="/books">Books</a></li>
|
<li {% if nav == "books" %}class = "nav-active"{% endif %}><a href="/books">Books</a></li>
|
||||||
<li><a href="/series">Series</a></li>
|
<li {% if nav == "series" %}class = "nav-active"{% endif %}><a href="/series">Series</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
|
</header>
|
||||||
|
<main class="container">
|
||||||
{% block content %}{% endblock content %}
|
{% block content %}{% endblock content %}
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
{% extends "base" %}
|
{% extends "base" %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<h1>Recent Books</h1>
|
|
||||||
<div class="grid-container">
|
<div class="grid-container">
|
||||||
{% for book in books %}
|
{% for book in books %}
|
||||||
{% include "book_card" %}
|
{% include "book_card" %}
|
||||||
|
Loading…
Reference in New Issue
Block a user