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

feat: add TryFromChunks impl for chrono_0_4::NaiveDate #94

Merged
merged 1 commit into from
Dec 3, 2024
Merged
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
37 changes: 37 additions & 0 deletions src/try_from_chunks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,34 @@
})
}
}
#[cfg(feature = "chrono_0_4")]
#[async_trait]
impl<Err> TryFromChunks for chrono_0_4::NaiveDate
where
Err: Into<anyhow::Error>,
chrono_0_4::NaiveDate: FromStr<Err = Err>,
{
async fn try_from_chunks(
chunks: impl Stream<Item = Result<Bytes, TypedMultipartError>> + Send + Sync + Unpin,
metadata: FieldMetadata,
) -> Result<Self, TypedMultipartError> {
let field_name = get_field_name(&metadata.name);
let bytes = Bytes::try_from_chunks(chunks, metadata).await?;
let body_str =
std::str::from_utf8(&bytes).map_err(|err| TypedMultipartError::WrongFieldType {
field_name: field_name.clone(),
wanted_type: type_name::<chrono_0_4::NaiveDate>().to_string(),
source: err.into(),

Check warning on line 208 in src/try_from_chunks.rs

View check run for this annotation

Codecov / codecov/patch

src/try_from_chunks.rs#L206-L208

Added lines #L206 - L208 were not covered by tests
})?;
chrono_0_4::NaiveDate::from_str(body_str).map_err(|err| {
TypedMultipartError::WrongFieldType {
field_name,
wanted_type: type_name::<chrono_0_4::NaiveDate>().to_string(),
source: err.into(),
}
})
}
}

fn get_field_name(name: &Option<String>) -> String {
// Theoretically, the name should always be present, but it's better to be
Expand All @@ -200,6 +228,7 @@
mod tests {
use super::*;
use bytes::Bytes;
use chrono_0_4::NaiveDate;
use futures_util::stream;
use std::fmt::Debug;
use std::io::Read;
Expand Down Expand Up @@ -370,6 +399,14 @@
test_try_from_chunks_invalid::<DateTime>(Bytes::from_static(&[0, 159, 146, 150])).await;
}

#[tokio::test]
async fn test_try_from_chunks_chrono_native_date_fixed() {
let valid_input = "2024-01-01";
let valid_output = NaiveDate::from_str(valid_input).unwrap();
test_try_from_chunks_valid::<NaiveDate>(valid_input, valid_output).await;
test_try_from_chunks_invalid::<NaiveDate>("invalid").await;
}

#[tokio::test]
async fn test_try_from_chunks_named_temp_file() {
let chunks = create_chunks("Hello, dear world!");
Expand Down
Loading