diff options
author | Guillermo Ramos | 2025-02-16 15:46:01 +0100 |
---|---|---|
committer | Guillermo Ramos | 2025-02-16 19:36:23 +0100 |
commit | 209adfe41e976919c290debbfd16cf81f5ba296e (patch) | |
tree | 341e1b78a55cf0c9933caa8d7f5fd8bb737ba863 /src | |
parent | 7d80d3d2be3e0f8e36be66a08879b1f04a381e88 (diff) | |
download | hiccup-209adfe41e976919c290debbfd16cf81f5ba296e.tar.gz |
Basic simulation API
Diffstat (limited to 'src')
-rw-r--r-- | src/bin/web.rs | 22 | ||||
-rw-r--r-- | src/lib.rs | 13 |
2 files changed, 28 insertions, 7 deletions
diff --git a/src/bin/web.rs b/src/bin/web.rs index 243e4a2..cc6b94f 100644 --- a/src/bin/web.rs +++ b/src/bin/web.rs @@ -1,7 +1,9 @@ +use hiccup::{SimUpdates, Simulation}; +use serde::Deserialize; use std::fs; use axum::{ - response::Html, + response::{Html, Json}, routing::get, Router, }; @@ -10,10 +12,26 @@ async fn root_get() -> Html<String> { Html(fs::read_to_string("front/index.html").unwrap()) } +#[derive(Deserialize)] +struct SimSpecs { + principal: f64, + i1: f64, + years: u32, +} + +async fn api_simulate_get<'a>(Json(specs): Json<SimSpecs>) -> Json<hiccup::Simulation<'a>> { + let mut sim = Simulation::new(specs.principal, specs.i1, specs.years); + let updates: SimUpdates = SimUpdates::default(); + sim.run(updates); + Json(sim) +} + #[tokio::main] async fn main() { // build our application with a single route - let app = Router::new().route("/", get(root_get)); + let app = Router::new() + .route("/", get(root_get)) + .route("/api/simulate", get(api_simulate_get)); // run our app with hyper, listening globally on port 3000 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); @@ -2,7 +2,9 @@ use std::collections::HashMap; use std::fmt; use std::ops::AddAssign; -#[derive(Clone, Copy)] +use serde::Serialize; + +#[derive(Clone, Copy, Serialize)] pub struct Capital { principal: f64, interest: f64, @@ -22,6 +24,7 @@ impl AddAssign for Capital { } } +#[derive(Serialize)] pub struct Simulation<'a> { st: SimState, updates: SimUpdates<'a>, @@ -140,7 +143,7 @@ impl<'a> Simulation<'a> { } } -#[derive(Clone)] +#[derive(Clone, Serialize)] struct SimState { period: u32, principal: f64, @@ -179,7 +182,7 @@ impl SimState { } } -#[derive(Clone)] +#[derive(Clone, Serialize)] pub struct Quota { period: u32, payed: Capital, @@ -206,7 +209,7 @@ impl fmt::Display for Quota { } } -#[derive(Debug, Default)] +#[derive(Debug, Default, Serialize)] pub struct SimUpdates<'a> { periodically: Vec<(u32, Vec<&'a SimUpdate>)>, by_month: HashMap<u32, Vec<&'a SimUpdate>>, @@ -247,7 +250,7 @@ impl<'a> SimUpdates<'a> { } } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Serialize)] pub enum SimUpdate { Amortize(f64), } |