mirror of
https://github.com/actix/examples
synced 2024-11-23 14:31:07 +01:00
feat: update example api to support GET /users (#629)
Co-authored-by: Rob Ede <robjtede@icloud.com>
This commit is contained in:
parent
18a8dbaa8f
commit
de0411ca31
@ -56,6 +56,21 @@ mod db {
|
||||
|
||||
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());
|
||||
@ -86,6 +101,14 @@ mod handlers {
|
||||
|
||||
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>,
|
||||
@ -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();
|
||||
|
Loading…
Reference in New Issue
Block a user