From 9c97b4465f5e5db14302664af76ae516017ea8c1 Mon Sep 17 00:00:00 2001 From: Zhen Lu Date: Wed, 3 Jan 2024 19:24:56 -0800 Subject: [PATCH] Add serializer and deserializer for NaiveDate --- lightspark/src/types/custom_date_formats.rs | 57 +++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/lightspark/src/types/custom_date_formats.rs b/lightspark/src/types/custom_date_formats.rs index 9381d85..abf9bb4 100644 --- a/lightspark/src/types/custom_date_formats.rs +++ b/lightspark/src/types/custom_date_formats.rs @@ -58,3 +58,60 @@ pub mod custom_date_format_option { } } } + +pub mod custom_date_only_format { + use chrono::NaiveDate; + use serde::{self, Deserialize, Deserializer, Serializer}; + + const FORMAT: &str = "%Y-%m-%d"; + + pub fn serialize(date: &NaiveDate, serializer: S) -> Result + where + S: Serializer, + { + let s = date.format(FORMAT).to_string(); + serializer.serialize_str(&s) + } + + pub fn deserialize<'de, D>(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + NaiveDate::parse_from_str(&s, FORMAT) + .map_err(|e| serde::de::Error::custom(format!("invalid date format: {}", e))) + } +} + +pub mod custom_date_only_format_option { + use chrono::NaiveDate; + use serde::{self, Deserialize, Deserializer, Serializer}; + + const FORMAT: &str = "%Y-%m-%d"; + + pub fn serialize(date: &Option, serializer: S) -> Result + where + S: Serializer, + { + match date { + Some(date) => { + let s = date.format(FORMAT).to_string(); + serializer.serialize_str(&s) + } + None => serializer.serialize_none(), + } + } + + pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + let s = Option::::deserialize(deserializer)?; + match s { + Some(s) => NaiveDate::parse_from_str(&s, FORMAT) + .map_err(|e| serde::de::Error::custom(format!("invalid date format: {}", e))) + .map(Some), + None => Ok(None), + } + } +}