diff options
Diffstat (limited to 'src/main.rs')
-rw-r--r-- | src/main.rs | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..f28d6df --- /dev/null +++ b/src/main.rs @@ -0,0 +1,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]), + "/", + ) +} |