use serde::{Deserialize, Serialize};
#[derive(sqlx::Type, Serialize, Deserialize, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
#[sqlx(transparent)]
pub struct Date(pub chrono::NaiveDate);
impl Date {
pub fn new(internal: chrono::NaiveDate) -> Self {
Self(internal)
}
pub fn from_ymd(year: i32, month: u32, day: u32) -> Self {
Self::new(
chrono::NaiveDate::from_ymd_opt(year, month, day).expect("Provided date is invalid."),
)
}
pub fn parse(s: &str) -> Result<Self, chrono::ParseError> {
chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").map(Self)
}
}
#[async_graphql::Object]
impl Date {
pub async fn year(&self) -> i32 {
use chrono::Datelike as _;
self.0.year()
}
pub async fn month(&self) -> u32 {
use chrono::Datelike as _;
self.0.month()
}
pub async fn day(&self) -> u32 {
use chrono::Datelike as _;
self.0.day()
}
pub async fn formatted_date(&self) -> String {
self.0.format("%B %e, %Y").to_string()
}
}
#[derive(async_graphql::InputObject)]
pub struct DateInput {
day: u32,
month: u32,
year: i32,
}
impl From<&DateInput> for Date {
fn from(val: &DateInput) -> Self {
Date::from_ymd(val.year, val.month, val.day)
}
}
impl From<DateInput> for Date {
fn from(di: DateInput) -> Self {
Date::from_ymd(di.year, di.month, di.day)
}
}
impl From<NaiveDate> for Date {
fn from(nd: NaiveDate) -> Self {
Date::new(nd)
}
}
use chrono::{Datelike, NaiveDate};
impl DateInput {
pub fn new(day: u32, month: u32, year: i32) -> Self {
Self { day, month, year }
}
pub fn parse_date_object(d: Date) -> Self {
let nd = d.0;
Self::new(nd.day(), nd.month(), nd.year())
}
}
#[derive(sqlx::Type, Serialize, Deserialize, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
#[sqlx(transparent)]
pub struct DateTime(pub chrono::NaiveDateTime);
impl DateTime {
pub fn new(internal: chrono::NaiveDateTime) -> Self {
Self(internal)
}
}
#[async_graphql::Object]
impl DateTime {
pub async fn timestamp(&self) -> i64 {
self.0.and_utc().timestamp()
}
pub async fn date(&self) -> Date {
Date::new(self.0.date())
}
}