1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-12-01 11:00:06 +01:00
actix-web/examples/diesel/src/db.rs

54 lines
1.2 KiB
Rust
Raw Normal View History

2017-12-21 02:43:43 +01:00
//! Db executor actor
use uuid;
use diesel;
use actix_web::*;
use actix::prelude::*;
use diesel::prelude::*;
use models;
use schema;
2018-01-16 19:59:33 +01:00
/// This is db executor actor. We are going to run 3 of them in parallel.
2017-12-21 02:43:43 +01:00
pub struct DbExecutor(pub SqliteConnection);
/// This is only message that this actor can handle, but it is easy to extend number of
/// messages.
pub struct CreateUser {
pub name: String,
}
impl ResponseType for CreateUser {
type Item = models::User;
type Error = Error;
}
impl Actor for DbExecutor {
type Context = SyncContext<Self>;
}
impl Handler<CreateUser> for DbExecutor {
2018-01-05 23:01:19 +01:00
type Result = MessageResult<CreateUser>;
fn handle(&mut self, msg: CreateUser, _: &mut Self::Context) -> Self::Result {
2017-12-21 02:43:43 +01:00
use self::schema::users::dsl::*;
let uuid = format!("{}", uuid::Uuid::new_v4());
let new_user = models::NewUser {
id: &uuid,
name: &msg.name,
};
diesel::insert_into(users)
.values(&new_user)
.execute(&self.0)
.expect("Error inserting person");
let mut items = users
.filter(id.eq(&uuid))
.load::<models::User>(&self.0)
.expect("Error loading person");
2018-01-05 23:01:19 +01:00
Ok(items.pop().unwrap())
2017-12-21 02:43:43 +01:00
}
}