|
@@ -3,18 +3,18 @@ use serde::Serialize;
|
|
|
use sqlx::{PgPool, postgres::PgQueryResult};
|
|
use sqlx::{PgPool, postgres::PgQueryResult};
|
|
|
use crate::app_error::AppError;
|
|
use crate::app_error::AppError;
|
|
|
|
|
|
|
|
-#[derive(Serialize)]
|
|
|
|
|
|
|
+#[derive(Serialize, sqlx::FromRow)]
|
|
|
pub struct Device {
|
|
pub struct Device {
|
|
|
- id: Uuid,
|
|
|
|
|
- home_id: Uuid,
|
|
|
|
|
- name: String,
|
|
|
|
|
- description: Option<String>,
|
|
|
|
|
- device_type: DeviceType
|
|
|
|
|
|
|
+ pub id: Uuid,
|
|
|
|
|
+ pub home_id: Uuid,
|
|
|
|
|
+ pub name: String,
|
|
|
|
|
+ pub description: Option<String>,
|
|
|
|
|
+ pub device_type: DeviceType
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
#[derive(Serialize, sqlx::Type)]
|
|
#[derive(Serialize, sqlx::Type)]
|
|
|
#[sqlx(type_name = "device_type", rename_all = "snake_case")]
|
|
#[sqlx(type_name = "device_type", rename_all = "snake_case")]
|
|
|
-enum DeviceType {
|
|
|
|
|
|
|
+pub enum DeviceType {
|
|
|
OnOffSwitch
|
|
OnOffSwitch
|
|
|
}
|
|
}
|
|
|
|
|
|
|
@@ -100,4 +100,30 @@ impl Device {
|
|
|
|
|
|
|
|
Ok(())
|
|
Ok(())
|
|
|
}
|
|
}
|
|
|
|
|
+
|
|
|
|
|
+ pub async fn find_one(
|
|
|
|
|
+ db: &PgPool,
|
|
|
|
|
+ user_id: Uuid,
|
|
|
|
|
+ home_id: Uuid,
|
|
|
|
|
+ device_id: Uuid,
|
|
|
|
|
+ ) -> Result<Device, AppError> {
|
|
|
|
|
+ let device = sqlx::query_as::<_, Device>(
|
|
|
|
|
+ "SELECT devices.*
|
|
|
|
|
+ FROM devices
|
|
|
|
|
+ JOIN users_homes ON users_homes.home_id = devices.home_id
|
|
|
|
|
+ WHERE devices.id = $1
|
|
|
|
|
+ AND devices.home_id = $2
|
|
|
|
|
+ AND users_homes.user_id = $3"
|
|
|
|
|
+ )
|
|
|
|
|
+ .bind(device_id)
|
|
|
|
|
+ .bind(home_id)
|
|
|
|
|
+ .bind(user_id)
|
|
|
|
|
+ .fetch_optional(db)
|
|
|
|
|
+ .await?;
|
|
|
|
|
+
|
|
|
|
|
+ match device {
|
|
|
|
|
+ Some(d) => Ok(d),
|
|
|
|
|
+ None => Err(AppError::forbidden("Unauthorized access to device"))
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|