Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update example api to support GET /users #629

Merged
merged 2 commits into from
Jul 22, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions databases/postgres/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,21 @@

use crate::{errors::MyError, models::User};

pub async fn get_users(client: &Client) -> Result<Vec<User>, 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::<Vec<User>>();

Ok(results)
}

pub async fn add_user(client: &Client, user_info: User) -> Result<User, MyError> {
let _stmt = include_str!("../sql/add_user.sql");
let _stmt = _stmt.replace("$table_fields", &User::sql_table_fields());
Expand Down Expand Up @@ -86,6 +101,14 @@

use crate::{db, errors::MyError, models::User};

pub async fn get_users(db_pool: web::Data<Pool>) -> Result<HttpResponse, Error> {
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<User>,
db_pool: web::Data<Pool>,
Expand All @@ -103,7 +126,7 @@
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;
Expand All @@ -119,12 +142,16 @@

let config: ExampleConfig = config_.try_deserialize().unwrap();

let pool = config.pg.create_pool(None, NoTls).unwrap();

Check warning on line 145 in databases/postgres/src/main.rs

View workflow job for this annotation

GitHub Actions / rustfmt check

Diff in /home/runner/work/examples/examples/databases/postgres/src/main.rs

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();
Expand Down
Loading