Skip to content

Commit

Permalink
Move the loading of db connections in handlers into its own helper fu…
Browse files Browse the repository at this point in the history
…nction
  • Loading branch information
jkcdarunday committed Aug 3, 2023
1 parent c3d558c commit fedfcce
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 10 deletions.
13 changes: 3 additions & 10 deletions src/app/api/users.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::app::db::DbPool;
use crate::app::error::AppError;
use crate::app::lib::helpers::get_connection;
use crate::app::models::*;
use crate::schema::users;
use actix_web::{get, post, web, HttpResponse, Responder, Result};
Expand All @@ -8,11 +9,7 @@ use diesel::prelude::*;

#[get("/users")]
pub async fn list(db_pool: web::Data<DbPool>) -> Result<impl Responder, AppError> {
let mut con = db_pool.get().map_err(|e| {
AppError::new(500)
.cause(e)
.message("Failed to load database")
})?;
let mut con = get_connection(db_pool)?;

let query_result = users::table
.load::<user::User>(&mut *con)
Expand All @@ -26,11 +23,7 @@ pub async fn create(
db_pool: web::Data<DbPool>,
user: web::Json<user::User>,
) -> Result<impl Responder, AppError> {
let mut con = db_pool.get().map_err(|e| {
AppError::new(500)
.cause(e)
.message("Failed to load database")
})?;
let mut con = get_connection(db_pool)?;

let query_result = insert_into(users::table)
.values((
Expand Down
1 change: 1 addition & 0 deletions src/app/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use diesel::r2d2::ConnectionManager;
use r2d2::Pool;

pub type DbPool = r2d2::Pool<ConnectionManager<PgConnection>>;
pub type DbPooledConnection = r2d2::PooledConnection<ConnectionManager<PgConnection>>;

pub fn get_connection_pool() -> DbPool {
let database_url: String = crate::app::config::get("database_url");
Expand Down
11 changes: 11 additions & 0 deletions src/app/lib/helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use crate::app::db::{DbPool, DbPooledConnection};
use crate::app::error::AppError;
use actix_web::web;

pub fn get_connection(db_pool: web::Data<DbPool>) -> Result<DbPooledConnection, AppError> {
db_pool.get().map_err(|e| {
AppError::new(500)
.cause(e)
.message("Failed to load database")
})
}
1 change: 1 addition & 0 deletions src/app/lib/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod helpers;
1 change: 1 addition & 0 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub mod config;
pub mod db;
pub mod error;
pub mod init;
pub mod lib;
pub mod route;

pub mod models {
Expand Down

0 comments on commit fedfcce

Please sign in to comment.