articles_rs/articles/
models.rsuse 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")?,
})
}
}