-
Notifications
You must be signed in to change notification settings - Fork 5
/
catalogue.rs
278 lines (251 loc) · 7.81 KB
/
catalogue.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use core::fmt;
use maud::{html, Markup, PreEscaped, Render};
use paginate::Pages;
use rusqlite::{Connection, OpenFlags, Result, ToSql};
use std::{
fmt::{Display, Formatter},
str::FromStr,
};
use strum_macros::EnumString;
use sublime_fuzzy::best_match;
use vercel_runtime::{run, Body, Error, Request, Response, StatusCode};
#[derive(EnumString, Debug)]
#[strum(serialize_all = "snake_case")]
enum Rating {
Masterpiece,
Loved,
Liked,
Okay,
Disliked,
Hated,
}
impl Render for Rating {
fn render(&self) -> Markup {
let rating = match self {
Rating::Masterpiece => "❤️",
Rating::Loved => "🥰",
Rating::Liked => "🙂",
Rating::Okay => "😐",
Rating::Disliked => "😕",
Rating::Hated => "🙁",
};
html! {
span."absolute top-0 right-0 pr-[0.15rem] pl-[0.2rem] bg-black/5 rounded-bl-lg" {
(rating)
}
}
}
}
#[derive(Debug)]
struct Cover {
src: String,
width: u32,
height: u32,
placeholder: String,
}
impl Render for Cover {
fn render(&self) -> Markup {
html! {
img."max-w-full h-auto aspect-[3/4.3] object-cover" width=(self.width) height=(self.height) src=(self.src)
loading="lazy" style={"background-size: cover;background-image: url(" (self.placeholder) ");image-rendering:auto;"}
onload="this.removeAttribute('style');this.removeAttribute('onload');" decoding="async";
}
}
}
#[derive(Debug)]
struct CatalogueEntry {
title: String,
author: String,
cover: Cover,
rating: Rating,
search_score: isize,
}
#[derive(Eq, PartialEq, serde::Deserialize, serde::Serialize, Debug)]
#[serde(rename_all = "snake_case")]
enum Sort {
Alphabetical,
Date,
Rating,
#[serde(untagged)]
Unknown(String),
}
#[derive(Debug, serde::Deserialize)]
struct QueryParams {
search: Option<String>,
sort: Option<Sort>,
r#type: Option<String>,
rating: Option<String>,
before: Option<String>,
after: Option<String>,
page: Option<usize>,
}
enum NextStatement {
And,
Where,
}
impl Display for NextStatement {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
NextStatement::And => write!(f, " AND "),
NextStatement::Where => write!(f, " WHERE "),
}
}
}
#[tokio::main]
async fn main() -> Result<(), Error> {
run(handler).await
}
pub async fn handler(_req: Request) -> Result<Response<Body>, Error> {
let conn = Connection::open_with_flags(
"./api/cataloguedb.db",
OpenFlags::SQLITE_OPEN_CREATE | OpenFlags::SQLITE_OPEN_READ_WRITE,
)?;
let query_params = match _req.uri().query() {
Some(query) => serde_qs::from_str::<QueryParams>(query)?,
None => QueryParams {
search: None,
sort: None,
r#type: None,
rating: None,
before: None,
after: None,
page: None,
},
};
let mut parameters: Vec<(&str, &dyn ToSql)> = Vec::new();
let mut next_statement = NextStatement::Where;
let mut statement = String::from(
"SELECT a.*, c.src, c.placeholder FROM Catalogue a
INNER JOIN Cover c
ON c.id = a.cover",
);
match query_params.rating {
Some(_) => {
parameters.push((":rating", &query_params.rating));
statement.push_str(format!("{} rating = :rating", next_statement).as_str());
next_statement = NextStatement::And;
}
None => (),
}
match query_params.r#type {
Some(_) => {
parameters.push((":type", &query_params.r#type));
statement.push_str(format!("{} type = :type", next_statement).as_str());
next_statement = NextStatement::And;
}
None => (),
}
match query_params.before {
Some(_) => {
parameters.push((":before", &query_params.before));
statement.push_str(format!("{} finishedDate < :before", next_statement).as_str());
next_statement = NextStatement::And;
}
None => (),
}
match query_params.after {
Some(_) => {
parameters.push((":after", &query_params.after));
statement.push_str(format!("{} finishedDate > :after", next_statement).as_str());
}
None => (),
}
match query_params.sort {
Some(Sort::Alphabetical) => {
statement.push_str(" ORDER BY a.title ASC, a.finishedDate DESC;");
}
Some(Sort::Rating) => {
statement.push_str(
" ORDER BY CASE
WHEN a.rating = 'masterpiece' THEN 1
WHEN a.rating = 'loved' THEN 2
WHEN a.rating = 'liked' THEN 3
WHEN a.rating = 'okay' THEN 4
WHEN a.rating = 'disliked' THEN 5
WHEN a.rating = 'hated' THEN 6
ELSE 7
END ASC, a.finishedDate DESC;",
);
}
_ => {
statement.push_str(" ORDER BY a.finishedDate DESC;");
}
}
let mut stmt = conn.prepare(&statement)?;
let mut catalogue_entries: Vec<CatalogueEntry> = stmt
.query_map(parameters.as_slice(), |row| {
Ok(CatalogueEntry {
title: row.get(2)?,
author: row.get(3)?,
cover: Cover {
src: row.get(9)?,
width: 240,
height: 360,
placeholder: row.get(10)?,
},
rating: Rating::from_str(row.get_ref(5).unwrap().as_str()?).unwrap(),
search_score: match &query_params.search {
Some(search) => {
let best_match =
match best_match(&search, &row.get_ref(2).unwrap().as_str()?) {
Some(best_match) => best_match.score(),
None => 0,
};
best_match
}
None => 0,
},
})
})?
.map(|cat| cat.unwrap())
.filter(|cat| match &query_params.search {
Some(_) => cat.search_score > 0,
None => true,
})
.collect();
match query_params.search {
Some(_) => {
catalogue_entries.sort_by(|a, b| b.search_score.cmp(&a.search_score));
}
None => (),
}
let total_items = catalogue_entries.len();
let items_per_page = 30usize;
let pages = Pages::new(total_items, items_per_page);
let page = pages.with_offset(query_params.page.unwrap_or(1) - 1);
catalogue_entries = catalogue_entries
.into_iter()
.skip(page.start)
.take(page.length)
.collect();
// Maud is sooo fun to use!!
let markup = html! {
"{"
(PreEscaped(" \"totalItems\": ")) (total_items) ","
(PreEscaped(" \"itemsPerPage\": ")) (items_per_page) ","
(PreEscaped(" \"currentPage\": ")) (page.offset) ","
(PreEscaped(" \"currentOffset\": ")) (page.start) ","
(PreEscaped(" \"totalPages\": ")) (pages.page_count())
"}"
"!METAEND"
@for entry in catalogue_entries {
div."w-[calc(50%-1rem)] sm:w-[calc(20%-1rem)]" {
div."relative" {
(entry.cover)
(entry.rating)
}
h4."m-0 leading-tight" {
(entry.title)
}
p."text-sm" {
(entry.author)
}
}
}
};
Ok(Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "text/html; charset=utf-8")
.header("Cache-Control", "max-age=3600, s-maxage=604800")
.body(markup.into_string().into())?)
}