Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(types-rs): parse election date as a date, not a datetime #90

Merged
merged 1 commit into from
Mar 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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