nle-cloud-sdk 0.1.1

Unofficial asynchronous Rust SDK for the NLECloud (新大陆物联网云平台) IoT platform
Documentation
//! Utility functions for datetime parsing and Serde serialization.

use chrono::NaiveDateTime;
use serde::{self, Deserialize, Deserializer, Serializer};

/// Format datetime using default API string format: `YYYY-MM-DD HH:mm:ss`
pub const DEFAULT_DATETIME_FORMAT: &str = "%Y-%m-%d %H:%M:%S";

/// Parses a date string trying common NLECloud date/time formats.
pub fn parse_flexible_datetime(s: &str) -> Option<NaiveDateTime> {
    let formats = [
        "%Y-%m-%d %H:%M:%S",
        "%Y-%m-%d %H:%M",
        "%Y/%m/%d %H:%M:%S",
        "%Y/%m/%d %H:%M",
        "%Y-%m-%dT%H:%M:%S",
        "%Y-%m-%d",
    ];

    for fmt in &formats {
        if let Ok(dt) = NaiveDateTime::parse_from_str(s, fmt) {
            return Some(dt);
        }
    }

    // Try parsing date only and assuming midnight
    if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
        return d.and_hms_opt(0, 0, 0);
    }
    if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y/%m/%d") {
        return d.and_hms_opt(0, 0, 0);
    }

    None
}

/// Serde helper for `Option<NaiveDateTime>`
pub mod flexible_datetime_opt {
    use super::*;

    /// Serializes an optional NaiveDateTime to standard NLECloud format.
    pub fn serialize<S>(date: &Option<NaiveDateTime>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match date {
            Some(dt) => serializer.serialize_str(&dt.format(DEFAULT_DATETIME_FORMAT).to_string()),
            None => serializer.serialize_none(),
        }
    }

    /// Deserializes a string into an optional NaiveDateTime supporting multiple formats.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<NaiveDateTime>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<String> = Option::deserialize(deserializer)?;
        match opt {
            Some(s) if !s.trim().is_empty() => {
                parse_flexible_datetime(s.trim()).map(Some).ok_or_else(|| {
                    serde::de::Error::custom(format!("failed to parse datetime: {}", s))
                })
            }
            _ => Ok(None),
        }
    }
}

/// Serde helper for `NaiveDateTime`
pub mod flexible_datetime {
    use super::*;

    /// Serializes a NaiveDateTime to standard NLECloud format.
    pub fn serialize<S>(date: &NaiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&date.format(DEFAULT_DATETIME_FORMAT).to_string())
    }

    /// Deserializes a string into a NaiveDateTime supporting multiple formats.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<NaiveDateTime, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        parse_flexible_datetime(s.trim())
            .ok_or_else(|| serde::de::Error::custom(format!("failed to parse datetime: {}", s)))
    }
}