From de0411ca31431add4576d1e6374d9cc3f8d69f16 Mon Sep 17 00:00:00 2001 From: Joey Figaro Date: Sat, 22 Jul 2023 17:28:57 -0400 Subject: [PATCH] feat: update example api to support GET /users (#629) Co-authored-by: Rob Ede --- databases/postgres/src/main.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/databases/postgres/src/main.rs b/databases/postgres/src/main.rs index 00a9948..910a3c4 100644 --- a/databases/postgres/src/main.rs +++ b/databases/postgres/src/main.rs @@ -56,6 +56,21 @@ mod db { use crate::{errors::MyError, models::User}; + pub async fn get_users(client: &Client) -> Result, MyError> { + let stmt = include_str!("../sql/get_users.sql"); + let stmt = stmt.replace("$table_fields", &User::sql_table_fields()); + let stmt = client.prepare(&stmt).await.unwrap(); + + let results = client + .query(&stmt, &[]) + .await? + .iter() + .map(|row| User::from_row_ref(row).unwrap()) + .collect::>(); + + Ok(results) + } + pub async fn add_user(client: &Client, user_info: User) -> Result { let _stmt = include_str!("../sql/add_user.sql"); let _stmt = _stmt.replace("$table_fields", &User::sql_table_fields()); @@ -86,6 +101,14 @@ mod handlers { use crate::{db, errors::MyError, models::User}; + pub async fn get_users(db_pool: web::Data) -> Result { + let client: Client = db_pool.get().await.map_err(MyError::PoolError)?; + + let users = db::get_users(&client).await?; + + Ok(HttpResponse::Ok().json(users)) + } + pub async fn add_user( user: web::Json, db_pool: web::Data, @@ -103,7 +126,7 @@ mod handlers { use ::config::Config; use actix_web::{web, App, HttpServer}; use dotenv::dotenv; -use handlers::add_user; +use handlers::{add_user, get_users}; use tokio_postgres::NoTls; use crate::config::ExampleConfig; @@ -124,7 +147,11 @@ async fn main() -> std::io::Result<()> { let server = HttpServer::new(move || { App::new() .app_data(web::Data::new(pool.clone())) - .service(web::resource("/users").route(web::post().to(add_user))) + .service( + web::resource("/users") + .route(web::post().to(add_user)) + .route(web::get().to(get_users)) + ) }) .bind(config.server_addr.clone())? .run();