Skip to content

Commit

Permalink
Room API (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
JijoBose authored Jan 21, 2024
1 parent 8154d10 commit 0aaa232
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 75 deletions.
121 changes: 49 additions & 72 deletions api/src/handlers/room.rs
Original file line number Diff line number Diff line change
@@ -1,85 +1,62 @@
use entity::house;
use entity::house::Entity as HouseEntity;

use axum::{
http::StatusCode,
Json, Extension, extract::Path,
};
use sea_orm::{DatabaseConnection, EntityTrait, Set, ActiveModelTrait};
use std::sync::Arc;

use crate::AppState;
use axum::extract::State;
use axum::{extract::Path, http::StatusCode, Json};
use entity::room;
use entity::room::Entity as RoomEntity;
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter, Set};
use uuid::Uuid;

use crate::models::house::{House, CreateHouse};
use crate::models::room::{CreateRoom, Room};

pub async fn all_houses(
Extension(database): Extension<DatabaseConnection>,
) -> Result<Json<Vec<House>>, StatusCode> {
pub async fn list_rooms(
State(database): State<Arc<AppState>>,
Path(house_id): Path<Uuid>,
) -> Result<Json<Vec<Room>>, StatusCode> {
let house_id = house_id.to_owned();

let list_houses = HouseEntity::find()
.all(&database)
let get_rooms = RoomEntity::find()
.filter(room::Column::HouseId.contains(house_id))
.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,
.map(|db_room| Room {
id: db_room.id.to_string(),
name: db_room.name,
house_id: db_room.house_id,
})
.collect();

Ok(Json(list_houses))
}

pub async fn create_house(
Extension(database): Extension<DatabaseConnection>,
Json(house_params): Json<CreateHouse>,
) -> Result<(), 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()
};

let _result = new_house
.save(&database)
.await
.unwrap();

Ok(())
Ok(Json(get_rooms))
}

pub async fn find_house(
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();

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

pub async fn delete_house(
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)?;

Ok(())
pub async fn create_rooms(
State(database): State<Arc<AppState>>,
Json(room_params): Json<CreateRoom>,
) -> Result<Json<Room>, StatusCode> {
let new_room = room::ActiveModel {
id: Set(Uuid::new_v4().to_string()),
name: Set(room_params.name),
house_id: Set(room_params.house_id),
};

match new_room.insert(&database.db).await {
Ok(inserted_room) => {
let response_json = Json(Room {
id: inserted_room.id,
name: inserted_room.name,
house_id: inserted_room.house_id,
});

Ok(response_json)
}
Err(db_err) => {
let status_code = match db_err {
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
Err(status_code)
}
}
}
4 changes: 2 additions & 2 deletions api/src/models/room.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ pub struct RoomQuery {

/// New room details.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewRoom {
pub struct CreateRoom {
pub name: String,
pub house_id: String,
}

// validations
impl NewRoom {
impl CreateRoom {
pub fn validate(&self) -> Result<(), String> {
if self.name.trim().is_empty() {
return Err("Name is empty".to_string());
Expand Down
15 changes: 14 additions & 1 deletion api/src/routes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,17 @@ use axum::{
};

use crate::AppState;
use crate::handlers::house::{all_houses, create_house, find_house, update_house, delete_house };
use crate::handlers::house::{
all_houses,
create_house,
find_house,
update_house,
delete_house
};
use crate::handlers::room::{
list_rooms,
create_rooms
};

pub fn create_routes(app_state: Arc<AppState>) -> Router {

Expand All @@ -16,5 +26,8 @@ pub fn create_routes(app_state: Arc<AppState>) -> Router {
.route("/houses/:id", get(find_house))
.route("/houses/:id", patch(update_house))
.route("/houses/:id", delete(delete_house))
// Rooms
.route("/rooms/:house_id", get(list_rooms))
.route("/rooms", post(create_rooms))
.with_state(app_state)
}

0 comments on commit 0aaa232

Please sign in to comment.