From 93356a10789d627a16d4cef613f16358a9762c2d Mon Sep 17 00:00:00 2001 From: Arjun Pratap Date: Sun, 5 Nov 2023 12:01:11 +0530 Subject: [PATCH] setup get users --- data.db | Bin 45056 -> 45056 bytes web_server/src/extensions.rs | 23 +++++++++++++++ web_server/src/main.rs | 53 ++++++++++++++++++++++++++++++----- 3 files changed, 69 insertions(+), 7 deletions(-) create mode 100644 web_server/src/extensions.rs diff --git a/data.db b/data.db index e7f5f66f70b62bfe67ab17a1dc52571eea364a69..662df3d208973c9c0b089d28d1b8aabc7ffbce2b 100644 GIT binary patch delta 308 zcmZp8z|`=7X@WGPz(g5mRsjaRtP2}c=Gt@fe`8?czsJCTkN@RnL4iyBvYd>};*6!m zsYS)i+)T`}90f)BS*gh-#S9D#T%4PK`*Rv_G4lsA@E_#w;tvLDapkW!WoBa#wH4R& z%TLY8OvzU8RL@mNR7lB8OG_KvAMiNn!z#wGhkl)6z1NGZS-iDiiZE^Rf~V)^Y)T!p#4Hf&UNx hH~tSmA3Wk0WMyV#WM&4DOiawooSa;n83q3H0{~4%TD<@O delta 78 zcmV-U0I~mo-~xc)0+1U44Urr}1q}c$Pkpguoj(fz0006H=>QM*59zZJ5Z4bF76@~3 kY+?%n104u(a&Ky7V{~%}0RtBZv-?j8FtY?;{2!ul5Qz2{V*mgE diff --git a/web_server/src/extensions.rs b/web_server/src/extensions.rs new file mode 100644 index 000000000..7b2858072 --- /dev/null +++ b/web_server/src/extensions.rs @@ -0,0 +1,23 @@ +use std::{slice::Iter, str::FromStr}; + +pub trait PairExt { + fn next_field(&mut self) -> T + where + T: FromStr, + ::Err: std::fmt::Debug; +} + +impl PairExt for Iter<'_, (&str, Option<&str>)> { + fn next_field(&mut self) -> T + where + T: FromStr, + ::Err: std::fmt::Debug, + { + self.next() + .expect("should exist") + .1 + .expect("should be not null") + .parse() + .expect("Should parse") + } +} diff --git a/web_server/src/main.rs b/web_server/src/main.rs index 9dc6b03ce..c167df6cb 100644 --- a/web_server/src/main.rs +++ b/web_server/src/main.rs @@ -1,13 +1,14 @@ +mod extensions; mod structs; + use axum::{ extract::State, http::StatusCode, - response::IntoResponse, routing::{get, post}, Json, Router, }; -use serde::{Deserialize, Serialize}; -use std::{net::SocketAddr, sync::Arc}; +use extensions::PairExt; +use std::{net::SocketAddr, slice::Iter, sync::Arc}; use structs::User; struct AppState { @@ -17,7 +18,7 @@ struct AppState { #[tokio::main] async fn main() { let shared_state = Arc::new(AppState { - conn: sqlite::Connection::open_with_full_mutex("../../data.db").expect("file should exist"), + conn: sqlite::Connection::open_with_full_mutex("../data.db").expect("file should exist"), }); tracing_subscriber::fmt::init(); @@ -27,7 +28,9 @@ async fn main() { .route("/", get(root)) // `POST /users` goes to `create_user` .route("/users", post(create_user)) - .with_state(shared_state); + .with_state(shared_state.clone()) + .route("/users", get(get_users)) + .with_state(shared_state.clone()); // run our app with hyper // `axum::Server` is a re-export of `hyper::Server` @@ -44,6 +47,37 @@ async fn root() -> &'static str { "Hello, World!" } +async fn get_users(State(state): State>) -> (StatusCode, Json>) { + let query = "SELECT * FROM users;"; + let mut users = Vec::new(); + let result = state.conn.iterate(query, |pairs| { + let mut pairs = pairs.into_iter(); + + let user = User { + id: Some( + pairs.next_field(), + // .expect("should exist") + // .1 + // .expect("should be not null") + // .parse() + // .expect("Should parse"), + ), + name: pairs.next_field(), + about: pairs.next_field(), + github: pairs.next_field(), + email: pairs.next_field(), + }; + users.push(user); + true + }); + + if let Err(e) = result { + println!("{}", e); + return (StatusCode::INTERNAL_SERVER_ERROR, Json(users)); + }; + (StatusCode::OK, Json(users)) +} + async fn create_user( // this argument tells axum to parse the request body // as JSON into a `CreateUser` type @@ -63,10 +97,15 @@ async fn create_user( .. } = payload; - let cmd = format!(r#"INSERT INTO users VALUES ("{name}", "{about}", "{github}", "{email}"))"#); + let cmd = format!( + r#"INSERT INTO users(name, about, github_link, email) VALUES ("{name}", "{about}", "{github}", "{email}")"# + ); match state.conn.execute(cmd) { Ok(_) => StatusCode::CREATED, // TODO: replace with better status code - Err(_) => StatusCode::IM_A_TEAPOT, + Err(err) => { + println!("{}", err); + StatusCode::INTERNAL_SERVER_ERROR + } } }