Skip to main content

apollo_configuration/types/
url.rs

1//! Support for URL types in configuration.
2//!
3//! Provides a [`Url`] newtype with appropriate error handling.
4
5use std::borrow::Cow;
6
7use derive_more::{Deref, Display, From, FromStr};
8use schemars::JsonSchema;
9use serde::de::Deserializer;
10use serde::{Deserialize, Serialize};
11
12use crate::Validate;
13
14/// A URL parsed from configuration.
15#[derive(Debug, Clone, PartialEq, Eq, Hash, Deref, From, FromStr, Display)]
16pub struct Url(url::Url);
17
18impl<'de> Deserialize<'de> for Url {
19    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
20    where
21        D: Deserializer<'de>,
22    {
23        let s = String::deserialize(deserializer)?;
24        url::Url::parse(&s)
25            .map(Self)
26            .map_err(serde::de::Error::custom)
27    }
28}
29
30impl Serialize for Url {
31    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
32    where
33        S: serde::Serializer,
34    {
35        self.0.as_str().serialize(serializer)
36    }
37}
38
39impl AsRef<str> for Url {
40    fn as_ref(&self) -> &str {
41        self.0.as_ref()
42    }
43}
44
45impl JsonSchema for Url {
46    fn schema_name() -> Cow<'static, str> {
47        Cow::Borrowed("Url")
48    }
49
50    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
51        url::Url::json_schema(generator)
52    }
53}
54
55impl Validate for Url {}