Add basic api

This commit is contained in:
Austen Adler 2023-02-25 18:30:15 -05:00
parent 9c341a67d6
commit d6f1506b31
4 changed files with 1499 additions and 1 deletions

1440
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -8,6 +8,7 @@ members = [
".", ".",
"./words", "./words",
"./this_algorithm-wasm/", "./this_algorithm-wasm/",
"./web",
] ]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

12
web/Cargo.toml Normal file
View File

@ -0,0 +1,12 @@
[package]
name = "web"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rocket = {version="0.5.0-rc.2", features=["json"]}
tokio = {version="1"}
this_algorithm={path=".."}
serde = {version="1", features=["derive"]}

47
web/src/main.rs Normal file
View File

@ -0,0 +1,47 @@
use std::str::FromStr;
use rocket::{get, routes, serde::json::Json};
use serde::{Deserialize, Serialize};
use this_algorithm::Address;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let _r = rocket::build()
// Add the API
.mount("/api/v1", routes![get_address, get_coords])
// Add the webui frontend
// TODO: ./mount("/", routes![webui])
.launch()
.await?;
Ok(())
}
#[get("/address?<lat>&<lon>")]
async fn get_address(lat: f64, lon: f64) -> Result<String, String> {
Address::from_lat_lon(lat, lon)
.map(|a| a.to_string())
.map_err(|e| e.to_string())
}
#[get("/coords?<address>")]
async fn get_coords(address: String) -> Result<Json<Coords>, String> {
Address::from_str(&address)
.as_ref()
.map(Address::to_lat_lon)
.map(Coords::from)
.map(Json)
.map_err(|e| e.to_string())
}
#[derive(Serialize, Deserialize)]
struct Coords {
lat: f64,
lon: f64,
}
impl From<(f64, f64)> for Coords {
fn from((lat, lon): (f64, f64)) -> Self {
Self { lat, lon }
}
}