1
0
mirror of https://github.com/actix/examples synced 2025-01-22 22:05:57 +01:00

fix diesel example (#460)

This commit is contained in:
fakeshadow 2021-10-22 15:47:12 +08:00 committed by GitHub
parent 414bf927b8
commit 261589ca87
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 18 deletions

View File

@ -14,7 +14,6 @@ dotenv = "0.15"
env_logger = "0.8"
failure = "0.1.8"
futures = "0.3.1"
r2d2 = "0.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
uuid = { version = "0.8", features = ["serde", "v4"] }

View File

@ -3,11 +3,13 @@ use uuid::Uuid;
use crate::models;
type DbError = Box<dyn std::error::Error + Send + Sync>;
/// Run query using Diesel to find user by uid and return it.
pub fn find_user_by_uid(
uid: Uuid,
conn: &SqliteConnection,
) -> Result<Option<models::User>, diesel::result::Error> {
) -> Result<Option<models::User>, DbError> {
use crate::schema::users::dsl::*;
let user = users
@ -23,7 +25,7 @@ pub fn insert_new_user(
// prevent collision with `name` column imported inside the function
nm: &str,
conn: &SqliteConnection,
) -> Result<models::User, diesel::result::Error> {
) -> Result<models::User, DbError> {
// It is common when using Diesel with Actix web to import schema-related
// modules inside a function's scope (rather than the normal module's scope)
// to prevent import collisions and namespace pollution.

View File

@ -24,10 +24,12 @@ async fn get_user(
user_uid: web::Path<Uuid>,
) -> Result<HttpResponse, Error> {
let user_uid = user_uid.into_inner();
let conn = pool.get().expect("couldn't get db connection from pool");
// use web::block to offload blocking Diesel code without blocking server thread
let user = web::block(move || actions::find_user_by_uid(user_uid, &conn))
let user = web::block(move || {
let conn = pool.get()?;
actions::find_user_by_uid(user_uid, &conn)
})
.await
.map_err(|e| {
eprintln!("{}", e);
@ -49,10 +51,11 @@ async fn add_user(
pool: web::Data<DbPool>,
form: web::Json<models::NewUser>,
) -> Result<HttpResponse, Error> {
let conn = pool.get().expect("couldn't get db connection from pool");
// use web::block to offload blocking Diesel code without blocking server thread
let user = web::block(move || actions::insert_new_user(&form.name, &conn))
let user = web::block(move || {
let conn = pool.get()?;
actions::insert_new_user(&form.name, &conn)
})
.await
.map_err(|e| {
eprintln!("{}", e);