summaryrefslogtreecommitdiff
path: root/src/models.rs
blob: 9e14b71dbf1196c9e8c70ce252c755492d2e2bc9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use strum::{EnumIter, IntoStaticStr};
use uuid::Uuid;

#[derive(sqlx::Type, Serialize, Deserialize, EnumIter, Debug, IntoStaticStr)]
#[sqlx(type_name = "metric_type")]
pub enum MetricType {
    BodyWeight,
    Hip,
    Waist,
}

#[derive(sqlx::Type, Serialize, Deserialize, EnumIter, Debug, IntoStaticStr)]
#[sqlx(type_name = "unit")]
pub enum Unit {
    Kilogram,
    Centimeter,
}

#[derive(Serialize)]
pub struct MeasurementView {
    pub id: Uuid,
    pub measured_at: DateTime<Utc>,
    pub metric_type: MetricType,
    pub value: f64,
    pub unit: Unit,
}

#[derive(Deserialize)]
#[serde(try_from = "MeasurementDataUnchecked")]
pub struct MeasurementData {
    pub measured_at: DateTime<Utc>,
    pub metric_type: MetricType,
    pub value: f64,
    pub unit: Unit,
}

#[derive(Deserialize)]
struct MeasurementDataUnchecked {
    pub measured_at: DateTime<Utc>,
    pub metric_type: MetricType,
    pub value: f64,
    pub unit: Unit,
}

impl TryFrom<MeasurementDataUnchecked> for MeasurementData {
    type Error = String;

    fn try_from(value: MeasurementDataUnchecked) -> Result<Self, Self::Error> {
        if value.value < 0.0 || value.value.is_nan() {
            return Err("Invalid value".to_string());
        }
        match (&value.metric_type, &value.unit) {
            (MetricType::BodyWeight, Unit::Kilogram)
            | (MetricType::Hip, Unit::Centimeter)
            | (MetricType::Waist, Unit::Centimeter) => Ok(Self {
                measured_at: value.measured_at,
                metric_type: value.metric_type,
                value: value.value,
                unit: value.unit,
            }),
            (metric_type, unit) => {
                let metric_type: &'static str = metric_type.into();
                let unit: &'static str = unit.into();
                Err(format!("Invalid pair {}, {}", metric_type, unit))
            }
        }
    }
}

#[derive(Deserialize)]
pub struct DateQuery {
    pub date: Option<NaiveDate>,
    pub from: Option<NaiveDate>,
    pub to: Option<NaiveDate>,
}

#[derive(Deserialize)]
pub struct AllQuery {
    pub limit: Option<i64>,
    pub reverse: Option<bool>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use sqlx::PgPool;
    use strum::IntoEnumIterator;

    #[sqlx::test]
    async fn unit_enums_match(pool: PgPool) {
        let values: Vec<Unit> = sqlx::query_scalar("SELECT enum_range(NULL::unit)")
            .fetch_one(&pool)
            .await
            .expect("Database has a variant that Rust doesn't");
        assert_eq!(
            values.len(),
            Unit::iter().count(),
            "Rust has a variant that the database doesn't"
        );
    }

    #[sqlx::test]
    async fn metric_type_enums_match(pool: PgPool) {
        let values: Vec<MetricType> = sqlx::query_scalar("SELECT enum_range(NULL::metric_type)")
            .fetch_one(&pool)
            .await
            .expect("Database has a variant that Rust doesn't");
        assert_eq!(
            values.len(),
            MetricType::iter().count(),
            "Rust has a variant that the database doesn't"
        );
    }
}