|
|
@@ -8,17 +8,33 @@ pub struct Device {
|
|
|
id: Uuid,
|
|
|
home_id: Uuid,
|
|
|
name: String,
|
|
|
- description: Option<String>
|
|
|
+ description: Option<String>,
|
|
|
+ device_type: DeviceType
|
|
|
+}
|
|
|
+
|
|
|
+#[derive(Serialize, sqlx::Type)]
|
|
|
+#[sqlx(type_name = "device_type", rename_all = "snake_case")]
|
|
|
+enum DeviceType {
|
|
|
+ OnOffSwitch
|
|
|
}
|
|
|
|
|
|
impl Device {
|
|
|
- pub fn new(home_id: Uuid, name: String, description: Option<String>) -> Self {
|
|
|
- Self {
|
|
|
+ pub fn new(
|
|
|
+ home_id: Uuid,
|
|
|
+ name: String,
|
|
|
+ description: Option<String>,
|
|
|
+ device_type: String
|
|
|
+ ) -> Result<Self, AppError> {
|
|
|
+ Ok(Self {
|
|
|
id: Uuid::now_v7(),
|
|
|
home_id: home_id,
|
|
|
name: name,
|
|
|
- description: description
|
|
|
- }
|
|
|
+ description: description,
|
|
|
+ device_type: match device_type.as_str() {
|
|
|
+ "on_off_switch" => DeviceType::OnOffSwitch,
|
|
|
+ _ => {return Err(AppError::invalid_input("Invalid device type"))}
|
|
|
+ }
|
|
|
+ })
|
|
|
}
|
|
|
|
|
|
pub async fn insert(
|
|
|
@@ -28,12 +44,12 @@ impl Device {
|
|
|
home_id: Uuid
|
|
|
) -> Result<(), AppError> {
|
|
|
let result: PgQueryResult = sqlx::query!(
|
|
|
- "INSERT INTO devices (id, home_id, name, description)
|
|
|
- SELECT $1, $2, $3, $4
|
|
|
+ "INSERT INTO devices (id, home_id, name, description, device_type)
|
|
|
+ SELECT $1, $2, $3, $4, $5
|
|
|
WHERE EXISTS (
|
|
|
SELECT 1
|
|
|
FROM users_homes
|
|
|
- WHERE user_id = $5
|
|
|
+ WHERE user_id = $6
|
|
|
AND home_id = $2
|
|
|
AND is_admin = true
|
|
|
)",
|
|
|
@@ -41,6 +57,7 @@ impl Device {
|
|
|
home_id,
|
|
|
self.name,
|
|
|
self.description,
|
|
|
+ &self.device_type as &DeviceType,
|
|
|
user_id
|
|
|
)
|
|
|
.execute(db)
|