Skip to content

Commit

Permalink
fix(types-rs): parse election date as a date, not a datetime (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
eventualbuddha authored Mar 26, 2024
1 parent ecc380d commit 558909f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
2 changes: 1 addition & 1 deletion libs/types-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ regex = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true, optional = true }
time = { workspace = true }
time = { workspace = true, features = ["parsing", "macros"] }
uuid = { workspace = true }

[dev-dependencies]
Expand Down
32 changes: 30 additions & 2 deletions libs/types-rs/src/election.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use hmac_sha256::Hash;
#[cfg(feature = "sqlx")]
use sqlx::Type;
use std::{fmt::Display, str::FromStr};
use time::macros::format_description;

use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -264,12 +265,39 @@ impl Serialize for PartialElectionHash {
}
}

mod election_date {
use super::*;
use serde::{de, Deserialize, Deserializer, Serializer};
use time::format_description;

const DATE_FORMATTER: &[format_description::FormatItem] =
format_description!("[year]-[month]-[day]");

pub fn serialize<S>(date: &time::Date, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date.format(DATE_FORMATTER)
.unwrap_or_default()
.serialize(serializer)
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<time::Date, D::Error>
where
D: Deserializer<'de>,
{
let date_str = String::deserialize(deserializer)?;
time::Date::parse(date_str.as_str(), DATE_FORMATTER)
.map_err(|e| de::Error::custom(format!("invalid date: {e}")))
}
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Election {
pub title: String,
#[serde(with = "time::serde::iso8601")]
pub date: time::OffsetDateTime,
#[serde(with = "election_date")]
pub date: time::Date,
pub ballot_styles: Vec<BallotStyle>,
pub precincts: Vec<Precinct>,
pub districts: Vec<District>,
Expand Down

0 comments on commit 558909f

Please sign in to comment.