Skip to content

Commit

Permalink
Add /div
Browse files Browse the repository at this point in the history
  • Loading branch information
turboladen committed Aug 2, 2024
1 parent 2eeb3b3 commit 4127690
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 2 deletions.
1 change: 1 addition & 0 deletions crates/web/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ impl Hooks for App {

fn routes(_ctx: &AppContext) -> AppRoutes {
AppRoutes::empty()
.add_route(controllers::div::routes())
.add_route(controllers::mul::routes())
.add_route(controllers::sub::routes())
.add_route(controllers::add::routes())
Expand Down
25 changes: 25 additions & 0 deletions crates/web/src/controllers/div.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#![allow(clippy::unused_async)]

use axum::debug_handler;
use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use tracing::debug;
use wise_units::Measurement;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Params {
lhs: Measurement,
rhs: Measurement,
}

#[debug_handler]
pub async fn div(Json(params): Json<Params>) -> impl IntoResponse {
debug!("Dividing {} * {}", &params.lhs, &params.rhs);

format::json(params.lhs / params.rhs)
}

pub fn routes() -> Routes {
Routes::new().prefix("div").add("/", post(div))
}

3 changes: 2 additions & 1 deletion crates/web/src/controllers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ pub mod home;
pub mod convert;
pub mod add;
pub mod sub;
pub mod mul;
pub mod mul;
pub mod div;
41 changes: 41 additions & 0 deletions crates/web/tests/requests/div.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

use loco_rs::testing;
use serial_test::serial;
use wise_units_web::app::App;

#[tokio::test]
#[serial]
async fn can_post_div_root() {
testing::request::<App, _, _>(|request, _ctx| async move {
let payload = serde_json::json!({
"lhs": {
"value": 10,
"unit": "km3"
},
"rhs": {
"value": 5,
"unit": "km2"
}
});

let expected = serde_json::json!({
"value": 2.0,
"unit": "km"
});
let res = request.post("/api/div").json(&payload).await;
assert_eq!(res.status_code(), 200);
assert_eq!(res.text(), serde_json::to_string(&expected).unwrap());
})
.await;
}

#[tokio::test]
#[serial]
async fn can_not_get_request_root() {
testing::request::<App, _, _>(|request, _ctx| async move {
let res = request.get("/api/div").await;
assert_eq!(res.status_code(), 405);
})
.await;
}

3 changes: 2 additions & 1 deletion crates/web/tests/requests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ mod home;
pub mod convert;
pub mod add;
pub mod sub;
pub mod mul;
pub mod mul;
pub mod div;

0 comments on commit 4127690

Please sign in to comment.