1use std::time::SystemTime;
4
5use serde::{Deserialize, Serialize};
6
7pub type JsonObject = serde_json::Map<String, serde_json::Value>;
10
11macro_rules! string_enum {
15 (
16 $(#[$meta:meta])*
17 $name:ident {
18 $( $(#[$variant_meta:meta])* $variant:ident => $wire:literal, )+
19 }
20 ) => {
21 $(#[$meta])*
22 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
23 #[non_exhaustive]
24 pub enum $name {
25 $( $(#[$variant_meta])* $variant, )+
26 Other(String),
29 }
30
31 impl $name {
32 #[must_use]
34 pub fn as_str(&self) -> &str {
35 match self {
36 $( Self::$variant => $wire, )+
37 Self::Other(other) => other,
38 }
39 }
40 }
41
42 impl std::fmt::Display for $name {
43 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 f.write_str(self.as_str())
45 }
46 }
47
48 impl serde::Serialize for $name {
49 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
50 serializer.serialize_str(self.as_str())
51 }
52 }
53
54 impl<'de> serde::Deserialize<'de> for $name {
55 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
56 let text = <String as serde::Deserialize>::deserialize(deserializer)?;
57 Ok(match text.as_str() {
58 $( $wire => Self::$variant, )+
59 _ => Self::Other(text),
60 })
61 }
62 }
63 };
64}
65pub(crate) use string_enum;
66
67string_enum! {
68 SortDirection {
70 Asc => "ASC",
72 Desc => "DESC",
74 }
75}
76
77pub(crate) fn to_object(
80 value: &impl Serialize,
81 what: &str,
82) -> std::result::Result<JsonObject, String> {
83 match serde_json::to_value(value) {
84 Ok(serde_json::Value::Object(object)) => Ok(object),
85 Ok(other) => Err(format!("{what} must be a JSON object, not {other}")),
86 Err(error) => Err(format!("{what} could not be serialized: {error}")),
87 }
88}
89
90#[derive(Clone, Debug, Deserialize)]
92#[serde(rename_all = "camelCase")]
93#[non_exhaustive]
94pub struct ResourceMeta {
95 pub id: String,
97 #[serde(deserialize_with = "crate::time::deserialize")]
99 pub created_at: SystemTime,
100 #[serde(deserialize_with = "crate::time::deserialize")]
102 pub updated_at: SystemTime,
103}
104
105#[derive(Clone, Debug, Deserialize)]
107#[non_exhaustive]
108pub struct Page<T> {
109 #[serde(default = "Vec::new")]
111 pub rows: Vec<T>,
112 #[serde(default)]
115 pub pagination: Option<Pagination>,
116}
117
118impl<T> Page<T> {
119 #[must_use]
122 pub fn has_next(&self) -> bool {
123 self.pagination.is_some_and(Pagination::has_next)
124 }
125}
126
127#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
131#[non_exhaustive]
132pub struct Pagination {
133 #[serde(default)]
135 pub current_page: Option<i64>,
136 #[serde(default)]
138 pub next_page: Option<i64>,
139 #[serde(default)]
141 pub num_pages: Option<i64>,
142}
143
144impl Pagination {
145 #[must_use]
147 pub fn has_next(self) -> bool {
148 matches!((self.current_page, self.num_pages), (Some(current), Some(pages)) if current < pages)
149 }
150}
151
152pub(crate) fn null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
157where
158 D: serde::Deserializer<'de>,
159 T: Default + serde::Deserialize<'de>,
160{
161 Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
162}
163
164#[cfg(test)]
165mod tests {
166 use super::*;
167
168 string_enum! {
169 Colour {
171 Red => "RED",
173 }
174 }
175
176 #[test]
177 fn a_string_enum_round_trips_known_and_unknown_values() {
178 assert_eq!(
179 serde_json::from_str::<Colour>(r#""RED""#).unwrap(),
180 Colour::Red
181 );
182 let other: Colour = serde_json::from_str(r#""MAUVE""#).unwrap();
183 assert_eq!(other, Colour::Other("MAUVE".into()));
184 assert_eq!(serde_json::to_string(&other).unwrap(), r#""MAUVE""#);
185 assert_eq!(Colour::Red.to_string(), "RED");
186 }
187
188 #[test]
189 fn a_page_tolerates_missing_rows_and_pagination() {
190 let page: Page<u8> = serde_json::from_str("{}").unwrap();
191 assert!(page.rows.is_empty());
192 assert!(page.pagination.is_none());
193 assert!(!page.has_next());
194 let page: Page<u8> = serde_json::from_str(
195 r#"{"rows":[1,2],"pagination":{"current_page":1,"next_page":2,"num_pages":3}}"#,
196 )
197 .unwrap();
198 assert_eq!(page.rows, [1, 2]);
199 assert!(page.has_next());
200 }
201
202 #[test]
203 fn the_last_page_has_no_next_even_though_next_page_counts_on() {
204 let page: Page<u8> = serde_json::from_str(
206 r#"{"rows":[],"pagination":{"current_page":2,"next_page":3,"num_pages":2}}"#,
207 )
208 .unwrap();
209 assert!(!page.has_next());
210 let page: Page<u8> = serde_json::from_str(
212 r#"{"rows":[],"pagination":{"current_page":0,"next_page":0,"num_pages":0}}"#,
213 )
214 .unwrap();
215 assert!(!page.has_next());
216 }
217}