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
|
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate diesel;
mod cors;
mod kanta;
mod pagination;
use crate::diesel::QueryDsl;
use crate::diesel::TextExpressionMethods;
use crate::pagination::SortingAndPaging;
use cors::CORS;
use rocket::serde::json::Json as InOut;
// use rocket::serde::msgpack::MsgPack as InOut;
#[derive(FromForm)]
struct ProductFilter {
prefix: Option<String>,
sort_by: Option<String>,
sort_direction: Option<String>,
page_num: Option<i64>,
page_size: Option<i64>,
}
#[get("/products?<filter..>")]
async fn filter_products(
filter: ProductFilter,
db: kanta::Db,
) -> Option<InOut<pagination::Page<kanta::Product>>> {
info!("prefix: {:?}", Some(filter.prefix.clone()));
db.run(move |conn| {
let mut query = kanta::products::table.into_boxed();
if let Some(i) = filter.prefix {
query = query.filter(kanta::products::title.like(format!("%{}%", i)));
}
query
.paginate(filter.page_num.unwrap_or(0))
.per_page(filter.page_size.unwrap_or(100))
.sort(
filter.sort_by.unwrap_or("created_at".to_string()),
filter.sort_direction.unwrap_or("".to_string()),
)
.load_and_count_items::<kanta::Product>(conn)
})
.await
.map(InOut)
.ok()
}
#[get("/")]
async fn index() -> String {
"Server is running".to_string()
}
#[launch]
fn rocket() -> _ {
kanta::mount_at(
rocket::build()
.attach(CORS)
.mount("/", routes![index, filter_products]),
"/",
)
}
|