summaryrefslogtreecommitdiff
path: root/src/models.rs
blob: 6b440402eb68688b8287c82f093e6bf857626254 (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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

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

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

impl MetricType {
    pub fn accepts(&self, unit: &Unit) -> bool {
        matches!(
            (self, unit),
            (MetricType::BodyWeight, Unit::Kilogram)
                | (MetricType::Hip, Unit::Centimeter)
                | (MetricType::Waist, Unit::Centimeter)
        )
    }
}

#[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());
        }
        if !value.metric_type.accepts(&value.unit) {
            let metric_type: &'static str = (&value.metric_type).into();
            let unit: &'static str = (&value.unit).into();
            return Err(format!("Invalid pair {}, {}", metric_type, unit));
        }
        Ok(Self {
            measured_at: value.measured_at,
            metric_type: value.metric_type,
            value: value.value,
            unit: value.unit,
        })
    }
}

#[derive(Serialize)]
pub struct MetricUnitPair {
    pub metric_type: MetricType,
    pub unit: Unit,
}

#[derive(Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Order {
    #[default]
    Asc,
    Desc,
}

#[derive(Deserialize)]
pub struct ListQuery {
    pub date: Option<NaiveDate>,
    pub from: Option<NaiveDate>,
    pub to: Option<NaiveDate>,
    pub limit: Option<i64>,
    #[serde(default)]
    pub order: Order,
}

#[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"
        );
    }
}