2022-02-06 08:25:38 +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};
|
2022-10-16 21:20:54 +01:00
|
|
|
use diesel::{
|
|
|
|
prelude::*,
|
|
|
|
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 || {
|
2022-09-10 23:33:09 +01:00
|
|
|
let mut conn = pool.get()?;
|
|
|
|
actions::find_user_by_uid(&mut conn, user_uid)
|
2021-10-22 15:47:12 +08:00
|
|
|
})
|
2022-01-31 02:46:08 +00:00
|
|
|
.await?
|
|
|
|
.map_err(actix_web::error::ErrorInternalServerError)?;
|
2020-01-27 12:20:04 +00:00
|
|
|
|
|
|
|
if let Some(user) = user {
|
|
|
|
Ok(HttpResponse::Ok().json(user))
|
|
|
|
} else {
|
2022-06-07 22:53:38 -04:00
|
|
|
let res = HttpResponse::NotFound().body(format!("No user found with uid: {user_uid}"));
|
2020-01-27 12:20:04 +00:00
|
|
|
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 || {
|
2022-09-10 23:33:09 +01:00
|
|
|
let mut conn = pool.get()?;
|
|
|
|
actions::insert_new_user(&mut conn, &form.name)
|
2021-10-22 15:47:12 +08:00
|
|
|
})
|
2022-01-31 02:46:08 +00:00
|
|
|
.await?
|
|
|
|
.map_err(actix_web::error::ErrorInternalServerError)?;
|
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<()> {
|
2019-06-12 23:03:20 +02:00
|
|
|
dotenv::dotenv().ok();
|
2022-02-18 02:32:44 +00:00
|
|
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
2019-06-12 23:03:20 +02:00
|
|
|
|
2020-01-27 12:20:04 +00:00
|
|
|
// set up database connection pool
|
2022-02-18 02:32:44 +00:00
|
|
|
let conn_spec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
|
|
|
|
let manager = ConnectionManager::<SqliteConnection>::new(conn_spec);
|
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
|
|
|
|
2022-02-18 02:32:44 +00:00
|
|
|
log::info!("starting HTTP server at http://localhost:8080");
|
2020-01-27 12:20:04 +00:00
|
|
|
|
|
|
|
// 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
|
2022-01-31 02:46:08 +00:00
|
|
|
.app_data(web::Data::new(pool.clone()))
|
2019-03-26 04:29:00 +01:00
|
|
|
.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
|
|
|
})
|
2022-02-18 02:32:44 +00:00
|
|
|
.bind(("127.0.0.1", 8080))?
|
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 actix_web::test;
|
|
|
|
|
2022-10-16 21:20:54 +01:00
|
|
|
use super::*;
|
|
|
|
|
2022-01-31 02:46:08 +00:00
|
|
|
#[actix_web::test]
|
2021-03-01 15:35:02 -03:00
|
|
|
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.");
|
|
|
|
|
2022-06-07 22:53:28 -04:00
|
|
|
let app = test::init_service(
|
2021-03-01 15:35:02 -03:00
|
|
|
App::new()
|
2022-01-31 02:46:08 +00:00
|
|
|
.app_data(web::Data::new(pool.clone()))
|
2021-03-01 15:35:02 -03:00
|
|
|
.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();
|
|
|
|
|
2022-06-07 22:53:28 -04:00
|
|
|
let resp: models::User = test::call_and_read_body_json(&app, req).await;
|
2021-03-01 15:35:02 -03:00
|
|
|
|
|
|
|
assert_eq!(resp.name, "Test user");
|
|
|
|
|
|
|
|
// Get a user
|
|
|
|
let req = test::TestRequest::get()
|
|
|
|
.uri(&format!("/user/{}", resp.id))
|
|
|
|
.to_request();
|
|
|
|
|
2022-06-07 22:53:28 -04:00
|
|
|
let resp: models::User = test::call_and_read_body_json(&app, req).await;
|
2021-03-01 15:35:02 -03:00
|
|
|
|
|
|
|
assert_eq!(resp.name, "Test user");
|
|
|
|
|
|
|
|
// Delete new user from table
|
|
|
|
use crate::schema::users::dsl::*;
|
|
|
|
diesel::delete(users.filter(id.eq(resp.id)))
|
2022-09-10 23:33:09 +01:00
|
|
|
.execute(&mut pool.get().expect("couldn't get db connection from pool"))
|
2021-03-01 15:35:02 -03:00
|
|
|
.expect("couldn't delete test user from table");
|
|
|
|
}
|
|
|
|
}
|