|
| 1 | +//! This module contains some custom serialization logic for the API. |
| 2 | +use std::sync::LazyLock; |
| 3 | + |
| 4 | +use regex::Regex; |
| 5 | +use serde::ser::SerializeSeq as _; |
| 6 | +use serde::{Serialize, Serializer}; |
| 7 | + |
| 8 | +/// A container for either a numeric ID or an alphanumeric slug. |
| 9 | +/// |
| 10 | +/// IDs are serialized as integers, while slugs are serialized as strings. |
| 11 | +#[derive(Serialize)] |
| 12 | +#[serde(untagged)] |
| 13 | +enum IdSlug<'s> { |
| 14 | + Id(i64), |
| 15 | + Slug(&'s str), |
| 16 | +} |
| 17 | + |
| 18 | +/// Serializes a sequence of strings, which may contain either numeric IDs or alphanumeric slugs. |
| 19 | +/// |
| 20 | +/// We check each element in the sequence. If the element only contains digits and can be parsed as a 64-bit signed integer, |
| 21 | +/// we consider the value to be an ID. Otherwise, we consider the value to be a slug. |
| 22 | +/// |
| 23 | +/// IDs are serialized as integers, while slugs are serialized as strings. |
| 24 | +pub fn serialize_id_slug_list<I, S>(list: I, serializer: S) -> Result<S::Ok, S::Error> |
| 25 | +where |
| 26 | + I: IntoIterator, |
| 27 | + I::Item: AsRef<str>, |
| 28 | + S: Serializer, |
| 29 | +{ |
| 30 | + let mut seq = serializer.serialize_seq(None)?; |
| 31 | + for item in list { |
| 32 | + let item = item.as_ref(); |
| 33 | + let id_slug = IdSlug::from(&item); |
| 34 | + seq.serialize_element(&id_slug)?; |
| 35 | + } |
| 36 | + seq.end() |
| 37 | +} |
| 38 | + |
| 39 | +impl<'a, S> From<&'a S> for IdSlug<'a> |
| 40 | +where |
| 41 | + S: AsRef<str>, |
| 42 | +{ |
| 43 | + /// Convert from a string reference to an IdSlug. |
| 44 | + /// |
| 45 | + /// If the string contains only digits and can be parsed as a 64-bit signed integer, |
| 46 | + /// we consider the value to be an ID. Otherwise, we consider the value to be a slug. |
| 47 | + fn from(value: &'a S) -> Self { |
| 48 | + /// Project ID regex |
| 49 | + /// |
| 50 | + /// Project IDs always contain only digits. |
| 51 | + static PROJECT_ID_REGEX: LazyLock<Regex> = |
| 52 | + LazyLock::new(|| Regex::new(r"^\d+$").expect("regex is valid")); |
| 53 | + |
| 54 | + let value = value.as_ref(); |
| 55 | + |
| 56 | + PROJECT_ID_REGEX |
| 57 | + .is_match(value) |
| 58 | + .then(|| value.parse().ok().map(IdSlug::Id)) |
| 59 | + .flatten() |
| 60 | + .unwrap_or(IdSlug::Slug(value)) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +#[cfg(test)] |
| 65 | +mod tests { |
| 66 | + use super::*; |
| 67 | + |
| 68 | + /// A test struct which serializes with serialize_id_slug_list |
| 69 | + #[derive(Serialize)] |
| 70 | + struct IdSlugListSerializerTest<const N: usize> { |
| 71 | + #[serde(serialize_with = "serialize_id_slug_list")] |
| 72 | + value: [&'static str; N], |
| 73 | + } |
| 74 | + |
| 75 | + #[test] |
| 76 | + fn test_serialize_id_slug_list_empty() { |
| 77 | + let to_serialize = IdSlugListSerializerTest { value: [] }; |
| 78 | + |
| 79 | + let serialized = serde_json::to_string(&to_serialize).unwrap(); |
| 80 | + let expected = serde_json::json!({ "value": [] }).to_string(); |
| 81 | + |
| 82 | + assert_eq!(serialized, expected) |
| 83 | + } |
| 84 | + |
| 85 | + #[test] |
| 86 | + fn test_serialize_id_slug_list_single_id() { |
| 87 | + let to_serialize = IdSlugListSerializerTest { value: ["123"] }; |
| 88 | + |
| 89 | + let serialized = serde_json::to_string(&to_serialize).unwrap(); |
| 90 | + let expected = serde_json::json!({ "value": [123] }).to_string(); |
| 91 | + |
| 92 | + assert_eq!(serialized, expected) |
| 93 | + } |
| 94 | + |
| 95 | + #[test] |
| 96 | + fn test_serialize_id_slug_list_single_slug() { |
| 97 | + let to_serialize = IdSlugListSerializerTest { value: ["abc"] }; |
| 98 | + |
| 99 | + let serialized = serde_json::to_string(&to_serialize).unwrap(); |
| 100 | + let expected = serde_json::json!({ "value": ["abc"] }).to_string(); |
| 101 | + |
| 102 | + assert_eq!(serialized, expected) |
| 103 | + } |
| 104 | + |
| 105 | + #[test] |
| 106 | + fn test_serialize_id_slug_list_multiple_ids_and_slugs() { |
| 107 | + let to_serialize = IdSlugListSerializerTest { |
| 108 | + value: ["123", "abc", "456", "whatever"], |
| 109 | + }; |
| 110 | + |
| 111 | + let serialized = serde_json::to_string(&to_serialize).unwrap(); |
| 112 | + let expected = serde_json::json!({ "value": [123, "abc", 456, "whatever"] }).to_string(); |
| 113 | + |
| 114 | + assert_eq!(serialized, expected) |
| 115 | + } |
| 116 | + |
| 117 | + /// Slugs of "-0" are possible. This test ensures that we serialize "-0" as a slug, |
| 118 | + /// rather than as an ID 0. |
| 119 | + #[test] |
| 120 | + fn test_serialize_id_slug_minus_zero_edge_case() { |
| 121 | + let to_serialize = IdSlugListSerializerTest { value: ["-0"] }; |
| 122 | + |
| 123 | + let serialized = serde_json::to_string(&to_serialize).unwrap(); |
| 124 | + let expected = serde_json::json!({ "value": ["-0"] }).to_string(); |
| 125 | + |
| 126 | + assert_eq!(serialized, expected) |
| 127 | + } |
| 128 | +} |
0 commit comments