Skip to main content

sunday_slate/media/
model.rs

1use time::PrimitiveDateTime;
2
3/// A media row's id as an opaque token: typed so it cannot be confused with
4/// other ids, open because the type distinction is the protection.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, sqlx::Type)]
6#[sqlx(transparent)]
7pub struct MediaId(pub i64);
8
9#[derive(Debug, Clone, PartialEq, sqlx::FromRow)]
10pub struct Media {
11    pub id: MediaId,
12    pub path: String,
13    pub content_type: String,
14    pub byte_size: i64,
15    pub width: i64,
16    pub height: i64,
17    pub created_at: PrimitiveDateTime,
18    pub updated_at: PrimitiveDateTime,
19}
20
21impl Media {
22    /// Public URL, e.g. `/media/7.png?v=...` — `v` is `updated_at` in epoch
23    /// nanos, so an in-place overwrite busts the cache.
24    pub fn url(&self) -> String {
25        let v = self.updated_at.assume_utc().unix_timestamp_nanos();
26        format!("/media/{path}?v={v}", path = self.path)
27    }
28}
29
30#[cfg(test)]
31impl Media {
32    pub fn fixture(path: &str, updated_at: PrimitiveDateTime) -> Media {
33        Media {
34            id: MediaId(7),
35            path: path.to_string(),
36            content_type: "image/png".to_string(),
37            byte_size: 1,
38            width: 256,
39            height: 256,
40            created_at: updated_at,
41            updated_at,
42        }
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49    use time::macros::datetime;
50
51    #[test]
52    fn url_builds_media_path_with_version() {
53        let url = Media::fixture("7.png", datetime!(2026-08-09 12:00:00)).url();
54        assert!(url.starts_with("/media/7.png?v="), "url = {url}");
55    }
56
57    #[test]
58    fn url_changes_when_updated_at_changes() {
59        let a = Media::fixture("7.png", datetime!(2026-08-09 12:00:00)).url();
60        let b = Media::fixture("7.png", datetime!(2026-08-09 12:00:01)).url();
61        assert_ne!(a, b);
62    }
63}