Skip to content

Commit

Permalink
feat(octez): implement deserialize for endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
huancheng-trili committed Nov 20, 2024
1 parent bf1af2d commit f5f8832
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions crates/octez/src/async/endpoint.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
use http::{uri::Scheme, Uri};
use serde::Serialize;
use std::fmt::{self, Display};
use serde_with::DeserializeFromStr;
use std::{
fmt::{self, Display},
str::FromStr,
};

#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone, PartialEq, DeserializeFromStr)]
pub struct Endpoint {
scheme: String,
host: String,
Expand Down Expand Up @@ -31,6 +35,15 @@ impl Endpoint {
}
}

impl FromStr for Endpoint {
type Err = anyhow::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let uri = Uri::from_str(s)?;
Endpoint::try_from(uri)
}
}

impl Serialize for Endpoint {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down Expand Up @@ -138,4 +151,22 @@ mod tests {
"\"http://localhost:8765\""
)
}

#[test]
fn deserialize() {
assert_eq!(
serde_json::from_str::<Endpoint>("\"http://localhost:8765\"").unwrap(),
Endpoint::localhost(8765)
);

assert_eq!(
serde_json::from_str::<Endpoint>("\"localhost:8765\"").unwrap(),
Endpoint::localhost(8765)
);

assert!(serde_json::from_str::<Endpoint>("{}")
.unwrap_err()
.to_string()
.contains("expected a string representing an URI"));
}
}

0 comments on commit f5f8832

Please sign in to comment.