graph_core/http/
response_builder_ext.rs

1use url::Url;
2
3#[derive(Debug, Clone, PartialEq)]
4pub(crate) struct HttpExtUrl(pub Url);
5
6#[derive(Debug, Clone, PartialEq)]
7pub(crate) struct HttpExtSerdeJsonValue(pub serde_json::Value);
8
9#[derive(Debug, Clone, PartialEq)]
10pub(crate) struct HttpExtVecU8(pub Vec<u8>);
11
12/// Extension trait for http::response::Builder objects
13///
14/// Allows the user to add a `Url` to the http::Response
15pub trait HttpResponseBuilderExt {
16    /// A builder method for the `http::response::Builder` type that allows the user to add a `Url`
17    /// to the `http::Response`
18    fn url(self, url: Url) -> Self;
19    fn json(self, value: &serde_json::Value) -> Self;
20}
21
22impl HttpResponseBuilderExt for http::response::Builder {
23    fn url(self, url: Url) -> Self {
24        self.extension(HttpExtUrl(url))
25    }
26
27    fn json(self, value: &serde_json::Value) -> Self {
28        if let Ok(value) = serde_json::to_vec(value) {
29            return self.extension(HttpExtVecU8(value));
30        }
31
32        self
33    }
34}
35
36pub trait HttpResponseExt {
37    fn url(&self) -> Option<Url>;
38    fn json(&self) -> Option<serde_json::Value>;
39}
40
41impl<T> HttpResponseExt for http::Response<T> {
42    fn url(&self) -> Option<Url> {
43        self.extensions()
44            .get::<HttpExtUrl>()
45            .map(|url| url.clone().0)
46    }
47
48    fn json(&self) -> Option<serde_json::Value> {
49        self.extensions()
50            .get::<HttpExtVecU8>()
51            .and_then(|value| serde_json::from_slice(value.0.as_slice()).ok())
52    }
53}