From f054130c1294d290f5be36be5db83d2b32baba8d Mon Sep 17 00:00:00 2001 From: Sebastian Pravda Date: Sun, 15 Jan 2023 20:00:56 +0100 Subject: [PATCH] refactor: NaiveDate parsing --- core/src/error.rs | 3 +++ core/src/models/candidate_details.rs | 4 ++-- core/src/utils/date.rs | 13 +++++++++++++ core/src/utils/mod.rs | 3 ++- 4 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 core/src/utils/date.rs diff --git a/core/src/error.rs b/core/src/error.rs index 2581fde..5273c4c 100644 --- a/core/src/error.rs +++ b/core/src/error.rs @@ -28,6 +28,8 @@ pub enum ServiceError { InternalServerError, #[error("Parrent not found")] ParentNotFound, + #[error("Invalid date")] + InvalidDate, #[error("Database error")] DbError(#[from] sea_orm::DbErr), #[error("Too many parents")] @@ -92,6 +94,7 @@ impl ServiceError { ServiceError::TooManyApplications => 409, // 500 ServiceError::InternalServerError => 500, + ServiceError::InvalidDate => 500, ServiceError::ParentNotFound => 500, ServiceError::DbError(_) => 500, ServiceError::UserNotFoundBySessionId => 500, diff --git a/core/src/models/candidate_details.rs b/core/src/models/candidate_details.rs index 5a470bf..65fd311 100644 --- a/core/src/models/candidate_details.rs +++ b/core/src/models/candidate_details.rs @@ -3,7 +3,7 @@ use chrono::NaiveDate; use entity::{candidate, parent}; use futures::future; -use crate::{crypto, models::candidate::{ApplicationDetails}, error::ServiceError}; +use crate::{crypto, models::candidate::{ApplicationDetails}, error::ServiceError, utils::date::parse_naive_date_from_opt_str}; use super::{candidate::{CandidateDetails, ParentDetails}, application::ApplicationRow}; @@ -171,7 +171,7 @@ impl EncryptedCandidateDetails { name: d.0.unwrap_or_default(), surname: d.1.unwrap_or_default(), birthplace: d.2.unwrap_or_default(), - birthdate: NaiveDate::parse_from_str(&d.3.unwrap_or_default(), NAIVE_DATE_FMT).unwrap_or(NaiveDate::from_ymd(1, 1, 1)), + birthdate: parse_naive_date_from_opt_str(d.3, NAIVE_DATE_FMT)?, address: d.4.unwrap_or_default(), telephone: d.5.unwrap_or_default(), citizenship: d.6.unwrap_or_default(), diff --git a/core/src/utils/date.rs b/core/src/utils/date.rs new file mode 100644 index 0000000..262755f --- /dev/null +++ b/core/src/utils/date.rs @@ -0,0 +1,13 @@ +use chrono::NaiveDate; + +use crate::error::ServiceError; + +pub fn parse_naive_date_from_opt_str(date: Option, fmt: &str) -> Result { + Ok( + NaiveDate::parse_from_str(&date.unwrap_or_default(), fmt) + .unwrap_or( + NaiveDate::from_ymd_opt(1, 1, 1) + .ok_or(ServiceError::InvalidDate)? + ) + ) +} \ No newline at end of file diff --git a/core/src/utils/mod.rs b/core/src/utils/mod.rs index d498f2d..8205ec2 100644 --- a/core/src/utils/mod.rs +++ b/core/src/utils/mod.rs @@ -1,3 +1,4 @@ pub mod csv; pub mod filetype; -pub mod db; \ No newline at end of file +pub mod db; +pub mod date; \ No newline at end of file