ソースを参照

Create route to get list of users homes

Lee Morgan 2 ヶ月 前
コミット
395d70c672
4 ファイル変更42 行追加5 行削除
  1. 17 0
      src/controllers/home/get_many.rs
  2. 1 0
      src/controllers/home/mod.rs
  3. 21 4
      src/models/home.rs
  4. 3 1
      src/routes/home.rs

+ 17 - 0
src/controllers/home/get_many.rs

@@ -0,0 +1,17 @@
+use actix_web::{HttpResponse, HttpRequest, web, get};
+use sqlx::PgPool;
+use crate::{
+    app_error::AppError,
+    auth::user_auth,
+    models::home::Home
+};
+
+#[get("/home")]
+pub async fn route(
+    db: web::Data<PgPool>,
+    req: HttpRequest
+) -> Result<HttpResponse, AppError> {
+    let user = user_auth(&db, &req).await?;
+    let homes = Home::get_many(&db, user.id).await?;
+    Ok(HttpResponse::Ok().json(homes))
+}

+ 1 - 0
src/controllers/home/mod.rs

@@ -1,2 +1,3 @@
 pub mod create;
 pub mod delete;
+pub mod get_many;

+ 21 - 4
src/models/home.rs

@@ -8,7 +8,8 @@ use crate::app_error::AppError;
 pub struct Home {
     pub id: Uuid,
     pub name: String,
-    pub created_at: DateTime<Utc>
+    pub created_at: DateTime<Utc>,
+    pub is_admin: Option<bool>
 }
 
 impl Home {
@@ -16,7 +17,8 @@ impl Home {
         Self {
             id: Uuid::now_v7(),
             name: name,
-            created_at: Utc::now()
+            created_at: Utc::now(),
+            is_admin: Some(true)
         }
     }
 
@@ -27,11 +29,12 @@ impl Home {
                 VALUES ($1, $2, $3)
             )
             INSERT INTO users_homes (user_id, home_id, is_admin)
-            VALUES ($4, $1, true)",
+            VALUES ($4, $1, $5)",
             self.id,
             self.name,
             self.created_at,
-            user_id
+            user_id,
+            self.is_admin.unwrap_or(false)
         )
             .execute(db)
             .await?;
@@ -58,4 +61,18 @@ impl Home {
             Ok(())
         }
     }
+
+    pub async fn get_many(db: &PgPool, user_id: Uuid) -> Result<Vec<Home>, AppError> {
+        let homes = sqlx::query_as!(
+            Home,
+            "SELECT homes.*, users_homes.is_admin FROM homes
+            JOIN users_homes ON users_homes.home_id = homes.id
+            WHERE users_homes.user_id = $1",
+            user_id
+        )
+            .fetch_all(db)
+            .await?;
+
+        Ok(homes)
+    }
 }

+ 3 - 1
src/routes/home.rs

@@ -1,10 +1,12 @@
 use actix_web::web;
 use crate::controllers::home::{
     create,
-    delete
+    delete,
+    get_many
 };
 
 pub fn config(cfg: &mut web::ServiceConfig) {
     cfg.service(create::route);
     cfg.service(delete::route);
+    cfg.service(get_many::route);
 }