refactor_serialization_deserialization_of_url

This commit is contained in:
Max Giga 2022-01-12 19:35:07 +03:00
parent ba2305dbe5
commit 834c54c1d6
2 changed files with 43 additions and 8 deletions

View file

@ -292,3 +292,45 @@ pub(crate) mod serde_date_from_unix_timestamp {
))
}
}
pub(crate) mod option_url_from_string {
use reqwest::Url;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub(crate) fn serialize<S>(this: &Option<Url>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
this.serialize(serializer)
}
pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Option<Url>, D::Error>
where
D: Deserializer<'de>,
{
Ok(reqwest::Url::deserialize(deserializer).ok())
}
#[test]
fn test() {
use std::str::FromStr;
#[derive(Serialize, Deserialize)]
struct Struct {
#[serde(with = "crate::types::option_url_from_string")]
url: Option<Url>,
}
{
let json = r#"{"url":""}"#;
let Struct { url } = serde_json::from_str(json).unwrap();
assert_eq!(url, None);
let json = r#"{"url":"https://github.com/token"}"#;
let Struct { url } = serde_json::from_str(json).unwrap();
assert_eq!(
url,
Some(Url::from_str("https://github.com/token").unwrap())
);
}
}
}

View file

@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct WebhookInfo {
#[serde(deserialize_with = "empty_string_to_url")]
#[serde(with = "crate::types::option_url_from_string")]
/// Webhook URL, `None` if webhook is not set up.
pub url: Option<reqwest::Url>,
@ -38,10 +38,3 @@ pub struct WebhookInfo {
/// types.
pub allowed_updates: Option<Vec<String>>,
}
fn empty_string_to_url<'de, D>(deserializer: D) -> Result<Option<reqwest::Url>, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(reqwest::Url::deserialize(deserializer).ok())
}