Skip to content

Commit

Permalink
List Rooms in a Home (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
JijoBose committed Jan 6, 2024
1 parent d4deaf5 commit 08d725c
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
8 changes: 8 additions & 0 deletions src/app/actions/room.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ use crate::app::models::room;

type DbError = Box<dyn std::error::Error + Send + Sync>;

pub fn list_rooms(conn: &mut PgConnection, uid: Uuid) -> Result<Vec<room::Room>, DbError> {
use crate::schema::rooms::dsl::*;

let room_list = rooms.filter(home_id.eq(uid.to_string())).load(conn)?;

Ok(room_list)
}

pub fn insert_new_room(
conn: &mut PgConnection,
form: &Json<room::NewRoom>,
Expand Down
19 changes: 18 additions & 1 deletion src/app/api/room.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use actix_web::{error, post, web, HttpResponse, Responder, Result};
use actix_web::{error, get, post, web, HttpResponse, Responder, Result};
use diesel::{r2d2, PgConnection};

use crate::app::actions;
Expand All @@ -20,3 +20,20 @@ async fn add_room(

Ok(HttpResponse::Created().json(response))
}

#[get("/room")]
async fn get_room(
pool: web::Data<DbPool>,
query: web::Query<models::room::RoomQuery>,
) -> Result<impl Responder> {
let home_uid = query.home_id;

let response = web::block(move || {
let mut conn = pool.get()?;
actions::room::list_rooms(&mut conn, home_uid)
})
.await?
.map_err(error::ErrorBadRequest)?;

Ok(HttpResponse::Ok().json(response))
}
6 changes: 6 additions & 0 deletions src/app/models/room.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use diesel::prelude::*;
use diesel::{prelude::Insertable, Queryable};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::schema::rooms;
use crate::app::models::home::Home;
Expand All @@ -15,6 +16,11 @@ pub struct Room {
pub home_id: String,
}

#[derive(Deserialize)]
pub struct RoomQuery {
pub home_id: Uuid,
}

/// New room details.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewRoom {
Expand Down
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use app::api::home::{
delete_home
};

use app::api::room::add_room;
use app::api::room::{add_room, get_room};

use app::db::{
initialize_db_pool,
Expand Down Expand Up @@ -40,6 +40,7 @@ async fn main() -> std::io::Result<()> {
.service(find_home)
.service(delete_home)
.service(add_room)
.service(get_room)
})
.bind(("127.0.0.1", 8080))?
.run()
Expand Down

0 comments on commit 08d725c

Please sign in to comment.