Skip to content

Commit

Permalink
Introduce api::v2::calendar::ListReqInit
Browse files Browse the repository at this point in the history
The api::v2::calendar::ListReq type doesn't have a logical default
implementation: the start and end date should always be provided. At the
same time, we would like to declare it as non-exhaustive to have some
better backward compatibility story moving forward.
To somehow unite these two constraints, this change introduces the
ListReqInit type, which implements Default and requires the start and
end date to be turned into the final ListReq.
  • Loading branch information
d-e-s-o committed Jul 26, 2024
1 parent de4b85f commit 17f4fb4
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions src/api/v2/calendar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,42 @@ pub struct ListReq {
// is not.
#[serde(rename = "end")]
pub end: NaiveDate,
/// The type is non-exhaustive and open to extension.
#[doc(hidden)]
#[serde(skip)]
pub _non_exhaustive: (),
}

impl From<Range<NaiveDate>> for ListReq {
fn from(range: Range<NaiveDate>) -> Self {
Self {
start: range.start,
end: range.end,
_non_exhaustive: (),
}
}
}


/// A helper for initializing [`ListReq`] objects.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[allow(missing_copy_implementations)]
pub struct ListReqInit {
/// The type is non-exhaustive and open to extension.
#[doc(hidden)]
pub _non_exhaustive: (),
}

impl ListReqInit {
/// Create a [`ListReq`] from a `ListReqInit`.
#[inline]
pub fn init(self, start: NaiveDate, end: NaiveDate) -> ListReq {
let Self { _non_exhaustive } = self;

ListReq {
start,
end,
_non_exhaustive: (),
}
}
}
Expand Down Expand Up @@ -147,10 +176,9 @@ mod tests {
/// Check that we can serialize and deserialize a [`CalendarReq`].
#[test]
fn serialize_deserialize_calendar_request() {
let request = ListReq {
start: NaiveDate::from_ymd_opt(2020, 4, 6).unwrap(),
end: NaiveDate::from_ymd_opt(2020, 4, 10).unwrap(),
};
let start = NaiveDate::from_ymd_opt(2020, 4, 6).unwrap();
let end = NaiveDate::from_ymd_opt(2020, 4, 10).unwrap();
let request = ListReqInit::default().init(start, end);

let json = to_json(&request).unwrap();
assert_eq!(from_json::<ListReq>(&json).unwrap(), request);
Expand Down

0 comments on commit 17f4fb4

Please sign in to comment.