feat: added event form & POST route

This commit is contained in:
Jef Roosens 2025-01-10 13:00:36 +01:00
parent 3add93bdb2
commit adef5c1fd5
Signed by: Jef Roosens
GPG key ID: 21FD3D77D56BAF49
13 changed files with 123 additions and 16 deletions

View file

@ -1,6 +1,6 @@
use std::{fmt::Display, str::FromStr};
use chrono::Utc;
use chrono::NaiveDate;
use r2d2_sqlite::rusqlite::{
self,
types::{FromSql, FromSqlError},
@ -8,6 +8,10 @@ use r2d2_sqlite::rusqlite::{
};
use serde::{Deserialize, Serialize};
use super::{DbError, DbPool};
pub const EVENT_TYPES: [&str; 1] = ["Watering"];
#[derive(Serialize, Deserialize)]
pub enum EventType {
Watering,
@ -63,17 +67,17 @@ pub struct Event {
id: i32,
plant_id: i32,
event_type: EventType,
time: chrono::DateTime<Utc>,
date: NaiveDate,
description: String,
}
impl Event {
pub fn from_row(row: Row<'_>) -> rusqlite::Result<Self> {
pub fn from_row(row: &Row<'_>) -> Result<Self, rusqlite::Error> {
Ok(Self {
id: row.get("id")?,
plant_id: row.get("plant_id")?,
event_type: row.get("event_type")?,
time: row.get("time")?,
date: row.get("date")?,
description: row.get("description")?,
})
}
@ -83,6 +87,26 @@ impl Event {
pub struct NewEvent {
plant_id: i32,
event_type: EventType,
time: chrono::DateTime<Utc>,
date: NaiveDate,
description: String,
}
impl NewEvent {
pub fn insert(self, pool: &DbPool) -> Result<Event, DbError> {
let conn = pool.get()?;
let mut stmt = conn.prepare(
"insert into events (plant_id, event_type, date, description) values ($1, $2, $3, $4) returning *",
)?;
Ok(stmt.query_row(
(
&self.plant_id,
&self.event_type,
&self.date,
&self.description,
),
Event::from_row,
)?)
}
}

View file

@ -7,6 +7,7 @@ use r2d2_sqlite::{rusqlite, SqliteConnectionManager};
use std::{error::Error, fmt};
pub use comment::{Comment, NewComment};
pub use event::{Event, EventType, NewEvent, EVENT_TYPES};
pub use plant::{NewPlant, Plant};
pub type DbPool = r2d2::Pool<SqliteConnectionManager>;

View file

@ -1,7 +1,7 @@
use r2d2_sqlite::rusqlite::{self, Row};
use serde::{Deserialize, Serialize};
use super::{Comment, DbError, DbPool};
use super::{Comment, DbError, DbPool, Event};
#[derive(Serialize)]
pub struct Plant {
@ -55,6 +55,14 @@ impl Plant {
let comments: Result<Vec<_>, _> = stmt.query_map((self.id,), Comment::from_row)?.collect();
Ok(comments?)
}
pub fn events(&self, pool: &DbPool) -> Result<Vec<Event>, DbError> {
let conn = pool.get()?;
let mut stmt = conn.prepare("select * from events where plant_id = $1")?;
let events: Result<Vec<_>, _> = stmt.query_map((self.id,), Event::from_row)?.collect();
Ok(events?)
}
}
impl NewPlant {