articles_rs/articles/
models.rs

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
use chrono::{DateTime, Utc};
use serde::Serialize;
use sqlx::{postgres::PgRow, FromRow, Row};
use uuid::Uuid;

#[derive(Debug, Serialize, Clone)]
pub struct Article {
    pub id: Option<Uuid>,
    pub title: String,
    pub slug: String,
    pub description: String,
    pub author: String,
    pub status: String,
    pub date: DateTime<Utc>,
    pub content: String,
}

impl Article {
    pub fn new(title: &str, slug: &str, description: &str, author: &str) -> Self {
        let now = Utc::now();
        Article {
            id: None,
            title: title.to_string(),
            slug: slug.to_string(),
            description: description.to_string(),
            author: author.to_string(),
            status: "NEW".to_string(),
            date: now,
            content: String::new(),
        }
    }
}

impl<'r> FromRow<'r, PgRow> for Article {
    fn from_row(row: &'r PgRow) -> Result<Self, sqlx::Error> {
        let row_id = row.try_get("id").ok();
        Ok(Article {
            id: row_id,
            title: row.try_get("title")?,
            slug: row.try_get("slug")?,
            description: row.try_get("description")?,
            author: row.try_get("author")?,
            status: row.try_get("status")?,
            date: row.try_get::<DateTime<Utc>, _>("date").unwrap_or_else(|_| {
                let naive_date: chrono::NaiveDateTime = row.try_get("date").unwrap();
                DateTime::<Utc>::from_naive_utc_and_offset(naive_date, Utc)
            }),
            content: row.try_get("content")?,
        })
    }
}