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

142 lines
4.8 KiB
Rust
Raw Normal View History

//! Actix web diesel example
//!
//! Diesel does not support tokio, so we have to run it in separate threads.
2018-05-08 11:08:43 -07:00
//! Actix supports sync actors by default, so we going to create sync actor
//! that use diesel. Technically sync actors are worker style actors, multiple
//! of them can run in parallel and process messages from same queue.
#[macro_use]
extern crate diesel;
2019-03-07 14:50:29 -08:00
#[macro_use]
extern crate serde_derive;
2019-03-07 14:50:29 -08:00
use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer};
use diesel::prelude::*;
2019-03-07 14:50:29 -08:00
use diesel::r2d2::{self, ConnectionManager};
use dotenv;
mod models;
mod schema;
2019-03-07 14:50:29 -08:00
type Pool = r2d2::Pool<ConnectionManager<SqliteConnection>>;
2019-12-09 06:28:09 +06:00
#[derive(Debug, Serialize, Deserialize)]
struct MyUser {
name: String,
}
2019-03-07 14:50:29 -08:00
/// Diesel query
fn query(
nm: String,
2019-03-16 20:23:09 -07:00
pool: web::Data<Pool>,
2019-03-07 14:50:29 -08:00
) -> Result<models::User, diesel::result::Error> {
use self::schema::users::dsl::*;
let uuid = format!("{}", uuid::Uuid::new_v4());
let new_user = models::NewUser {
id: &uuid,
name: nm.as_str(),
};
let conn: &SqliteConnection = &pool.get().unwrap();
2019-03-07 14:50:29 -08:00
diesel::insert_into(users).values(&new_user).execute(conn)?;
let mut items = users.filter(id.eq(&uuid)).load::<models::User>(conn)?;
Ok(items.pop().unwrap())
}
/// Async request handler
2019-12-07 23:59:24 +06:00
async fn add(
2019-03-07 14:50:29 -08:00
name: web::Path<String>,
2019-03-16 20:23:09 -07:00
pool: web::Data<Pool>,
2019-12-07 23:59:24 +06:00
) -> Result<HttpResponse, Error> {
2019-03-07 14:50:29 -08:00
// run diesel blocking code
2019-12-07 23:59:24 +06:00
Ok(web::block(move || query(name.into_inner(), pool))
.await
.map(|user| HttpResponse::Ok().json(user))
.map_err(|_| HttpResponse::InternalServerError())?)
}
2019-12-09 06:28:09 +06:00
/// This handler manually parse json object. Bytes object supports FromRequest trait (extractor)
/// and could be loaded from request payload automatically
2019-12-15 22:55:54 +06:00
async fn index_add(
body: web::Bytes,
pool: web::Data<Pool>,
) -> Result<HttpResponse, Error> {
2019-12-09 06:28:09 +06:00
// body is loaded, now we can deserialize id with serde-json
2019-12-07 23:59:24 +06:00
let r_obj = serde_json::from_slice::<MyUser>(&body);
// Send to the db for create return response to peer
match r_obj {
Ok(obj) => {
let user = web::block(move || query(obj.name, pool))
.await
.map_err(|_| Error::from(HttpResponse::InternalServerError()))?;
Ok(HttpResponse::Ok().json(user))
}
Err(_) => Err(error::ErrorBadRequest("Json Decode Failed")),
}
}
2019-12-09 06:28:09 +06:00
/// This handler offloads json deserialization to actix-web's Json extrator
2019-12-07 23:59:24 +06:00
async fn add2(
2019-03-07 14:50:29 -08:00
item: web::Json<MyUser>,
2019-03-16 20:23:09 -07:00
pool: web::Data<Pool>,
2019-12-07 23:59:24 +06:00
) -> Result<HttpResponse, Error> {
2019-03-07 14:50:29 -08:00
// run diesel blocking code
2019-12-07 23:59:24 +06:00
let user = web::block(move || query(item.into_inner().name, pool))
.await
.map_err(|_| HttpResponse::InternalServerError())?; // convert diesel error to http response
Ok(HttpResponse::Ok().json(user))
}
2019-12-07 23:59:24 +06:00
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
2019-03-07 14:50:29 -08:00
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
dotenv::dotenv().ok();
let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
let manager = ConnectionManager::<SqliteConnection>::new(connspec);
2018-05-08 11:08:43 -07:00
let pool = r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.");
// Start http server
2019-03-07 14:50:29 -08:00
HttpServer::new(move || {
App::new()
2019-03-26 04:29:00 +01:00
.data(pool.clone())
// enable logger
2019-03-26 04:29:00 +01:00
.wrap(middleware::Logger::default())
// This can be called with:
// curl -S --header "Content-Type: application/json" --request POST --data '{"name":"xyz"}' http://127.0.0.1:8080/add
// Use of the extractors makes some post conditions simpler such
// as size limit protections and built in json validation.
2019-03-07 14:50:29 -08:00
.service(
2019-05-04 21:52:24 -07:00
web::resource("/add2")
.data(
web::JsonConfig::default()
.limit(4096) // <- limit size of the payload
.error_handler(|err, _| {
// <- create custom error response
error::InternalError::from_response(
err,
HttpResponse::Conflict().finish(),
)
.into()
}),
)
2019-12-07 23:59:24 +06:00
.route(web::post().to(add2)),
2019-03-07 14:50:29 -08:00
)
// Manual parsing would allow custom error construction, use of
// other parsers *beside* json (for example CBOR, protobuf, xml), and allows
// an application to standardise on a single parser implementation.
2019-12-07 23:59:24 +06:00
.service(web::resource("/add").route(web::post().to(index_add)))
.service(web::resource("/add/{name}").route(web::get().to(add)))
2019-03-07 14:50:29 -08:00
})
.bind("127.0.0.1:8080")?
2019-12-07 23:59:24 +06:00
.start()
.await
}