Skip to content

Commit

Permalink
Axum and SeaORM Rewrite
Browse files Browse the repository at this point in the history
  • Loading branch information
JijoBose committed Jan 19, 2024
1 parent fd521b3 commit a4bdf35
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 79 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ name: Rust
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

env:
CARGO_TERM_COLOR: always
Expand Down
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,3 @@ Built with Axum and SeaORM
**Update Entity**

``sea-orm-cli generate entity -u postgres://jijobose:password@localhost/loco_app -o src/database/``

138 changes: 61 additions & 77 deletions src/api/house.rs
Original file line number Diff line number Diff line change
@@ -1,111 +1,95 @@
use std::sync::Arc;

use crate::{database::house::Entity as HouseEntity, AppState};
use crate::database::house;
use crate::{database::house::Entity as HouseEntity, AppState};
use axum::extract::State;
use axum::response::IntoResponse;
use axum::{
http::StatusCode,
Json, Extension, extract::Path,
};
use serde_json::json;
use sea_orm::{DatabaseConnection, EntityTrait, Set, ActiveModelTrait};
use axum::{extract::Path, http::StatusCode, Extension, Json};
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, Set};
use uuid::Uuid;

use crate::models::house::{House, CreateHouse};

use crate::models::house::{CreateHouse, House};

pub async fn all_houses(
State(database): State<Arc<AppState>>,
State(database): State<Arc<AppState>>,
) -> Result<Json<Vec<House>>, StatusCode> {

let list_houses = HouseEntity::find()
.all(&database.db)
.await
.map_err(|_error| StatusCode::INTERNAL_SERVER_ERROR)?
.into_iter()
.map(|db_house| House {
id: db_house.id.to_string(),
title: db_house.title,
body: db_house.body,
id: db_house.id.to_string(),
title: db_house.title,
body: db_house.body,
})
.collect();

Ok(Json(list_houses))
}

pub async fn create_house(
State(database): State<Arc<AppState>>,
Json(house_params): Json<CreateHouse>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {

let new_house = house::ActiveModel {
id: Set(Uuid::new_v4().to_string()),
title: Set(house_params.title),
body: Set(house_params.body),
..Default::default()
};

let result = new_house
.save(&database.db)
.await;

match result {
Ok(_) => {
let house_response = json!({ "status": "success" });

return Ok((StatusCode::CREATED, Json(house_response)));
State(database): State<Arc<AppState>>,
Json(house_params): Json<CreateHouse>,
) -> Result<Json<House>, StatusCode> {
let new_house = house::ActiveModel {
id: Set(Uuid::new_v4().to_string()),
title: Set(house_params.title),
body: Set(house_params.body),
..Default::default()
};

match new_house.insert(&database.db).await {
Ok(inserted_house) => {
let response_json = Json(House {
id: inserted_house.id,
title: inserted_house.title,
body: inserted_house.body,
});

Ok(response_json)
}
Err(db_err) => {
let status_code = match db_err {
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
Err(status_code)
}
}
Err(e) => {
if e.to_string()
.contains("duplicate key value violates unique constraint")
{
let error_response = serde_json::json!({
"status": "fail",
"message": "Note with that title already exists",
});
return Err((StatusCode::CONFLICT, Json(error_response)));
}
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"status": "error","message": format!("{:?}", e)})),
));
}

}
}

// Todo - Database implementation required
pub async fn find_house(
Extension(database): Extension<DatabaseConnection>,
Path(house_id): Path<Uuid>
Extension(database): Extension<DatabaseConnection>,
Path(house_id): Path<Uuid>,
) -> Result<Json<House>, StatusCode> {
let house_id = house_id.to_owned();

let house = HouseEntity::find_by_id(house_id)
.one(&database)
.await
.unwrap();
let house_id = house_id.to_owned();

if let Some(house) = house {
Ok(Json(House {
id: house.id.to_string(),
title: house.title,
body: house.body
}))
} else {
Err(StatusCode::NOT_FOUND)
}
let house = HouseEntity::find_by_id(house_id)
.one(&database)
.await
.unwrap();

if let Some(house) = house {
Ok(Json(House {
id: house.id.to_string(),
title: house.title,
body: house.body,
}))
} else {
Err(StatusCode::NOT_FOUND)
}
}

// Todo - Database implementation required
pub async fn delete_house(
Extension(database): Extension<DatabaseConnection>,
Path(house_id): Path<Uuid>
Extension(database): Extension<DatabaseConnection>,
Path(house_id): Path<Uuid>,
) -> Result<(), StatusCode> {
let house_id = house_id.to_owned();
HouseEntity::delete_by_id(house_id)
.exec(&database)
.await
.map_err(|_error| StatusCode::INTERNAL_SERVER_ERROR)?;
let house_id = house_id.to_owned();
HouseEntity::delete_by_id(house_id)
.exec(&database)
.await
.map_err(|_error| StatusCode::INTERNAL_SERVER_ERROR)?;

Ok(())
Ok(())
}
2 changes: 1 addition & 1 deletion src/models/house.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl CreateHouse {
return Err("Name is empty".to_string());
}
if self.body.trim().is_empty() {
return Err("Desciption is empty".to_string());
return Err("Description is empty".to_string());
}
Ok(())
}
Expand Down

0 comments on commit a4bdf35

Please sign in to comment.