1
0
mirror of https://github.com/actix/examples synced 2025-02-02 17:39:05 +01:00

132 lines
3.7 KiB
Rust
Raw Normal View History

mod config {
pub use ::config::ConfigError;
2020-01-31 07:21:39 -05:00
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Config {
pub server_addr: String,
pub pg: deadpool_postgres::Config,
}
impl Config {
pub fn from_env() -> Result<Self, ConfigError> {
let mut cfg = ::config::Config::new();
cfg.merge(::config::Environment::new())?;
cfg.try_into()
}
}
}
2020-01-15 19:19:15 -05:00
mod models {
use serde::{Deserialize, Serialize};
use tokio_pg_mapper_derive::PostgresMapper;
#[derive(Deserialize, PostgresMapper, Serialize)]
#[pg_mapper(table = "users")] // singular 'user' is a keyword..
pub struct User {
pub email: String,
pub first_name: String,
pub last_name: String,
2020-01-16 06:46:28 -05:00
pub username: String,
2020-01-15 19:19:15 -05:00
}
}
mod errors {
2020-01-16 06:46:28 -05:00
use actix_web::{HttpResponse, ResponseError};
use deadpool_postgres::PoolError;
use derive_more::{Display, From};
use tokio_pg_mapper::Error as PGMError;
use tokio_postgres::error::Error as PGError;
#[derive(Display, From, Debug)]
pub enum MyError {
NotFound,
PGError(PGError),
PGMError(PGMError),
PoolError(PoolError),
}
impl std::error::Error for MyError {}
impl ResponseError for MyError {
fn error_response(&self) -> HttpResponse {
match *self {
MyError::NotFound => HttpResponse::NotFound().finish(),
2020-01-31 07:21:39 -05:00
MyError::PoolError(ref err) => {
HttpResponse::InternalServerError().body(err.to_string())
}
2020-01-16 06:46:28 -05:00
_ => HttpResponse::InternalServerError().finish(),
}
}
}
2020-01-15 19:19:15 -05:00
}
mod db {
2020-01-16 06:46:28 -05:00
use crate::{errors::MyError, models::User};
use deadpool_postgres::Client;
use tokio_pg_mapper::FromTokioPostgresRow;
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());
let stmt = client.prepare(&_stmt).await.unwrap();
client
.query(
&stmt,
&[
&user_info.email,
&user_info.first_name,
&user_info.last_name,
&user_info.username,
],
)
.await?
.iter()
.map(|row| User::from_row_ref(row).unwrap())
.collect::<Vec<User>>()
.pop()
.ok_or(MyError::NotFound) // more applicable for SELECTs
}
2020-01-15 19:19:15 -05:00
}
mod handlers {
use crate::{db, errors::MyError, models::User};
2020-01-16 06:46:28 -05:00
use actix_web::{web, Error, HttpResponse};
use deadpool_postgres::{Client, Pool};
2020-01-15 19:19:15 -05:00
2020-01-16 06:46:28 -05:00
pub async fn add_user(
user: web::Json<User>,
db_pool: web::Data<Pool>,
) -> Result<HttpResponse, Error> {
let user_info: User = user.into_inner();
2020-01-15 19:19:15 -05:00
2020-04-03 16:16:17 +09:00
let client: Client = db_pool.get().await.map_err(MyError::PoolError)?;
2020-01-31 07:21:39 -05:00
2020-01-16 06:46:28 -05:00
let new_user = db::add_user(&client, user_info).await?;
2020-01-15 19:19:15 -05:00
2020-01-16 06:46:28 -05:00
Ok(HttpResponse::Ok().json(new_user))
}
2020-01-15 19:19:15 -05:00
}
2020-01-16 06:46:28 -05:00
use actix_web::{web, App, HttpServer};
use dotenv::dotenv;
2020-01-15 19:19:15 -05:00
use handlers::add_user;
2020-01-31 07:21:39 -05:00
use tokio_postgres::NoTls;
2020-01-15 19:19:15 -05:00
2020-09-12 16:49:45 +01:00
#[actix_web::main]
2020-01-15 19:19:15 -05:00
async fn main() -> std::io::Result<()> {
dotenv().ok();
2020-01-15 19:19:15 -05:00
let config = crate::config::Config::from_env().unwrap();
let pool = config.pg.create_pool(None, NoTls).unwrap();
2020-01-15 19:19:15 -05:00
2020-01-16 06:46:28 -05:00
let server = HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone()))
2020-01-16 06:46:28 -05:00
.service(web::resource("/users").route(web::post().to(add_user)))
})
.bind(config.server_addr.clone())?
2020-01-16 06:46:28 -05:00
.run();
println!("Server running at http://{}/", config.server_addr);
2020-01-15 19:19:15 -05:00
server.await
}