2020-01-27 12:20:04 +00:00
|
|
|
//! Actix web Diesel integration example
|
2018-04-13 09:18:42 +08:00
|
|
|
//!
|
2020-01-27 12:20:04 +00:00
|
|
|
//! Diesel does not support tokio, so we have to run it in separate threads using the web::block
|
|
|
|
//! function which offloads blocking code (like Diesel's) in order to not block the server's thread.
|
|
|
|
|
2018-04-13 09:18:42 +08:00
|
|
|
#[macro_use]
|
|
|
|
extern crate diesel;
|
|
|
|
|
2020-01-27 12:20:04 +00:00
|
|
|
use actix_web::{get, middleware, post, web, App, Error, HttpResponse, HttpServer};
|
2018-04-13 09:18:42 +08:00
|
|
|
use diesel::prelude::*;
|
2019-03-07 14:50:29 -08:00
|
|
|
use diesel::r2d2::{self, ConnectionManager};
|
2020-01-27 12:20:04 +00:00
|
|
|
use uuid::Uuid;
|
2018-04-13 09:18:42 +08:00
|
|
|
|
2020-01-27 12:20:04 +00:00
|
|
|
mod actions;
|
2018-04-13 09:18:42 +08:00
|
|
|
mod models;
|
|
|
|
mod schema;
|
|
|
|
|
2020-01-27 12:20:04 +00:00
|
|
|
type DbPool = r2d2::Pool<ConnectionManager<SqliteConnection>>;
|
2018-04-13 09:18:42 +08:00
|
|
|
|
2020-01-27 12:20:04 +00:00
|
|
|
/// Finds user by UID.
|
|
|
|
#[get("/user/{user_id}")]
|
|
|
|
async fn get_user(
|
|
|
|
pool: web::Data<DbPool>,
|
|
|
|
user_uid: web::Path<Uuid>,
|
2019-12-07 23:59:24 +06:00
|
|
|
) -> Result<HttpResponse, Error> {
|
2020-01-27 12:20:04 +00:00
|
|
|
let user_uid = user_uid.into_inner();
|
2019-12-07 23:59:24 +06:00
|
|
|
|
2020-01-27 12:20:04 +00:00
|
|
|
// use web::block to offload blocking Diesel code without blocking server thread
|
2021-10-22 15:47:12 +08:00
|
|
|
let user = web::block(move || {
|
|
|
|
let conn = pool.get()?;
|
|
|
|
actions::find_user_by_uid(user_uid, &conn)
|
|
|
|
})
|
|
|
|
.await
|
|
|
|
.map_err(|e| {
|
|
|
|
eprintln!("{}", e);
|
|
|
|
HttpResponse::InternalServerError().finish()
|
|
|
|
})?;
|
2020-01-27 12:20:04 +00:00
|
|
|
|
|
|
|
if let Some(user) = user {
|
|
|
|
Ok(HttpResponse::Ok().json(user))
|
|
|
|
} else {
|
|
|
|
let res = HttpResponse::NotFound()
|
|
|
|
.body(format!("No user found with uid: {}", user_uid));
|
|
|
|
Ok(res)
|
2019-12-07 23:59:24 +06:00
|
|
|
}
|
2019-01-31 19:12:27 +13:00
|
|
|
}
|
|
|
|
|
2020-01-27 12:20:04 +00:00
|
|
|
/// Inserts new user with name defined in form.
|
|
|
|
#[post("/user")]
|
|
|
|
async fn add_user(
|
|
|
|
pool: web::Data<DbPool>,
|
|
|
|
form: web::Json<models::NewUser>,
|
2019-12-07 23:59:24 +06:00
|
|
|
) -> Result<HttpResponse, Error> {
|
2020-01-27 12:20:04 +00:00
|
|
|
// use web::block to offload blocking Diesel code without blocking server thread
|
2021-10-22 15:47:12 +08:00
|
|
|
let user = web::block(move || {
|
|
|
|
let conn = pool.get()?;
|
|
|
|
actions::insert_new_user(&form.name, &conn)
|
|
|
|
})
|
|
|
|
.await
|
|
|
|
.map_err(|e| {
|
|
|
|
eprintln!("{}", e);
|
|
|
|
HttpResponse::InternalServerError().finish()
|
|
|
|
})?;
|
2019-12-07 23:59:24 +06:00
|
|
|
|
|
|
|
Ok(HttpResponse::Ok().json(user))
|
2019-01-31 19:12:27 +13:00
|
|
|
}
|
|
|
|
|
2020-09-12 16:49:45 +01:00
|
|
|
#[actix_web::main]
|
2019-12-07 23:59:24 +06:00
|
|
|
async fn main() -> std::io::Result<()> {
|
2020-05-20 19:34:41 +08:00
|
|
|
std::env::set_var("RUST_LOG", "actix_web=info");
|
2018-04-13 09:18:42 +08:00
|
|
|
env_logger::init();
|
2019-06-12 23:03:20 +02:00
|
|
|
dotenv::dotenv().ok();
|
|
|
|
|
2020-01-27 12:20:04 +00:00
|
|
|
// set up database connection pool
|
2019-06-12 23:03:20 +02:00
|
|
|
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.");
|
2018-04-13 09:18:42 +08:00
|
|
|
|
2020-01-27 12:20:04 +00:00
|
|
|
let bind = "127.0.0.1:8080";
|
|
|
|
|
|
|
|
println!("Starting server at: {}", &bind);
|
|
|
|
|
|
|
|
// Start HTTP server
|
2019-03-07 14:50:29 -08:00
|
|
|
HttpServer::new(move || {
|
|
|
|
App::new()
|
2020-01-27 12:20:04 +00:00
|
|
|
// set up DB pool to be used with web::Data<Pool> extractor
|
2019-03-26 04:29:00 +01:00
|
|
|
.data(pool.clone())
|
|
|
|
.wrap(middleware::Logger::default())
|
2020-01-27 12:20:04 +00:00
|
|
|
.service(get_user)
|
|
|
|
.service(add_user)
|
2019-03-07 14:50:29 -08:00
|
|
|
})
|
2020-01-27 12:20:04 +00:00
|
|
|
.bind(&bind)?
|
2019-12-25 20:48:33 +04:00
|
|
|
.run()
|
2019-12-07 23:59:24 +06:00
|
|
|
.await
|
2018-04-13 09:18:42 +08:00
|
|
|
}
|
2021-03-01 15:35:02 -03:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
use actix_web::test;
|
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn user_routes() {
|
|
|
|
std::env::set_var("RUST_LOG", "actix_web=debug");
|
|
|
|
env_logger::init();
|
|
|
|
dotenv::dotenv().ok();
|
|
|
|
|
|
|
|
let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
|
|
|
|
let manager = ConnectionManager::<SqliteConnection>::new(connspec);
|
|
|
|
let pool = r2d2::Pool::builder()
|
|
|
|
.build(manager)
|
|
|
|
.expect("Failed to create pool.");
|
|
|
|
|
|
|
|
let mut app = test::init_service(
|
|
|
|
App::new()
|
|
|
|
.data(pool.clone())
|
|
|
|
.wrap(middleware::Logger::default())
|
|
|
|
.service(get_user)
|
|
|
|
.service(add_user),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
|
|
|
|
// Insert a user
|
|
|
|
let req = test::TestRequest::post()
|
|
|
|
.uri("/user")
|
|
|
|
.set_json(&models::NewUser {
|
|
|
|
name: "Test user".to_owned(),
|
|
|
|
})
|
|
|
|
.to_request();
|
|
|
|
|
|
|
|
let resp: models::User = test::read_response_json(&mut app, req).await;
|
|
|
|
|
|
|
|
assert_eq!(resp.name, "Test user");
|
|
|
|
|
|
|
|
// Get a user
|
|
|
|
let req = test::TestRequest::get()
|
|
|
|
.uri(&format!("/user/{}", resp.id))
|
|
|
|
.to_request();
|
|
|
|
|
|
|
|
let resp: models::User = test::read_response_json(&mut app, req).await;
|
|
|
|
|
|
|
|
assert_eq!(resp.name, "Test user");
|
|
|
|
|
|
|
|
// Delete new user from table
|
|
|
|
use crate::schema::users::dsl::*;
|
|
|
|
diesel::delete(users.filter(id.eq(resp.id)))
|
|
|
|
.execute(&pool.get().expect("couldn't get db connection from pool"))
|
|
|
|
.expect("couldn't delete test user from table");
|
|
|
|
}
|
|
|
|
}
|