Skip to content

Commit

Permalink
No longer pass around a DBConnection for EntityApi, but AppState instead
Browse files Browse the repository at this point in the history
  • Loading branch information
jhodapp committed Nov 30, 2023
1 parent 92f9727 commit 7a065c5
Show file tree
Hide file tree
Showing 8 changed files with 26 additions and 12 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions entity_api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ edition = "2021"

[dependencies]
entity = { path = "../entity" }
service = { path = "../service" }
serde_json = "1.0.107"
log = "0.4.20"

Expand Down
3 changes: 2 additions & 1 deletion entity_api/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub struct Error {

#[derive(Debug)]
pub enum EntityApiErrorType {
DatabaseConnectionLost,
// Record not found
RecordNotFound,
// Record not updated
Expand Down Expand Up @@ -50,7 +51,7 @@ impl From<DbErr> for Error {
},
DbErr::Conn(_) => Error {
inner: err,
error_type: EntityApiErrorType::SystemError,
error_type: EntityApiErrorType::DatabaseConnectionLost,
},
DbErr::Exec(_) => Error {
inner: err,
Expand Down
6 changes: 3 additions & 3 deletions entity_api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use sea_orm::DatabaseConnection;
use service::AppState;

pub mod error;
pub mod organization;

pub async fn seed_database(db: &DatabaseConnection) {
organization::seed_database(db).await;
pub async fn seed_database(app_state: &AppState) {
organization::seed_database(app_state).await;
}
13 changes: 9 additions & 4 deletions entity_api/src/organization.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,32 @@
use super::error::Error;
use entity::organization;
use organization::{Entity, Model};
use sea_orm::{entity::prelude::*, ActiveValue, DatabaseConnection};
use sea_orm::{entity::prelude::*, ActiveValue};
use serde_json::json;
use service::AppState;

pub async fn find_all(db: &DatabaseConnection) -> Vec<Model> {
pub async fn find_all(app_state: &AppState) -> Vec<Model> {
let db = app_state.database_connection.as_ref().unwrap();
Entity::find().all(db).await.unwrap_or(vec![])
}

pub async fn find_by_id(db: &DatabaseConnection, id: i32) -> Result<Option<Model>, Error> {
pub async fn find_by_id(app_state: &AppState, id: i32) -> Result<Option<Model>, Error> {
let db = app_state.database_connection.as_ref().unwrap();
Entity::find_by_id(id)
.one(db)
.await
.map_err(|err| err.into())
}

pub(crate) async fn seed_database(db: &DatabaseConnection) {
pub(crate) async fn seed_database(app_state: &AppState) {
let organization_names = [
"Jim Hodapp Coaching",
"Caleb Coaching",
"Enterprise Software",
];

let db = app_state.database_connection.as_ref().unwrap();

for name in organization_names {
let organization = organization::ActiveModel::from_json(json!({
"name": name,
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ async fn main() {
let mut app_state = AppState::new(config);
app_state = service::init_database(app_state).await.unwrap();

entity_api::seed_database(app_state.database_connection.as_ref().unwrap()).await;
entity_api::seed_database(&app_state).await;

web::init_server(app_state).await.unwrap();
}
Expand Down
5 changes: 2 additions & 3 deletions web/src/controller/organization_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ impl OrganizationController {
/// --request GET \
/// http://localhost:4000/organizations
pub async fn index(State(app_state): State<AppState>) -> impl IntoResponse {
let organizations =
OrganizationApi::find_all(&app_state.database_connection.unwrap()).await;
let organizations = OrganizationApi::find_all(&app_state).await;

Json(organizations)
}
Expand All @@ -36,7 +35,7 @@ impl OrganizationController {
debug!("GET Organization by id: {}", id);

let organization: Result<Option<organization::Model>, Error> =
OrganizationApi::find_by_id(&app_state.database_connection.unwrap(), id)
OrganizationApi::find_by_id(&app_state, id)
.await
.map_err(|err| err.into());

Expand Down
7 changes: 7 additions & 0 deletions web/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, Serialize)]

pub enum Error {
DatabaseConnectionLost,
InternalServer,
EntityNotFound,
UnprocessableEntity,
Expand All @@ -28,6 +29,11 @@ impl std::fmt::Display for Error {
impl IntoResponse for Error {
fn into_response(self) -> Response {
match self {
Error::DatabaseConnectionLost => (
StatusCode::INTERNAL_SERVER_ERROR,
"DB CONNECTION LOST - INTERNAL SERVER ERROR",
)
.into_response(),
Error::InternalServer => {
(StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL SERVER ERROR").into_response()
}
Expand All @@ -42,6 +48,7 @@ impl IntoResponse for Error {
impl From<EntityApiError> for Error {
fn from(err: EntityApiError) -> Self {
match err.error_type {
EntityApiErrorType::DatabaseConnectionLost => Error::DatabaseConnectionLost,
EntityApiErrorType::RecordNotFound => Error::EntityNotFound,
EntityApiErrorType::RecordNotUpdated => Error::UnprocessableEntity,
EntityApiErrorType::SystemError => Error::InternalServer,
Expand Down

0 comments on commit 7a065c5

Please sign in to comment.