noosphere_core/api/
data.rs

1use std::str::FromStr;
2
3use anyhow::Result;
4
5use serde::{Deserialize, Deserializer};
6
7/// A helper to express the deserialization of a query string to some
8/// consistent result type
9pub trait AsQuery {
10    /// Get the value of this trait implementor as a [Result<Option<String>>]
11    fn as_query(&self) -> Result<Option<String>>;
12}
13
14impl AsQuery for () {
15    fn as_query(&self) -> Result<Option<String>> {
16        Ok(None)
17    }
18}
19
20// NOTE: Adapted from https://github.com/tokio-rs/axum/blob/7caa4a3a47a31c211d301f3afbc518ea2c07b4de/examples/query-params-with-empty-strings/src/main.rs#L42-L54
21/// Serde deserialization decorator to map empty Strings to None,
22pub(crate) fn empty_string_as_none<'de, D, T>(de: D) -> Result<Option<T>, D::Error>
23where
24    D: Deserializer<'de>,
25    T: FromStr,
26    T::Err: std::fmt::Display,
27{
28    let opt = Option::<String>::deserialize(de)?;
29    match opt.as_deref() {
30        None | Some("") => Ok(None),
31        Some(s) => FromStr::from_str(s)
32            .map_err(serde::de::Error::custom)
33            .map(Some),
34    }
35}