unleash_api_client/http/
shim.rs

1//! Shim traits to define an external client as an unleash HTTP client This is
2//! an imperfect system, but sufficient to work with multiple async frameworks,
3//! which is the goal.
4
5// Copyright 2022 Cognite AS
6
7use core::fmt::{Debug, Display};
8use std::error::Error;
9
10use async_trait::async_trait;
11use serde::{de::DeserializeOwned, Serialize};
12
13/// Abstraction over the concrete HTTP client being used. Implement this on any
14/// type to use it as an HTTP client.
15#[async_trait]
16pub trait HttpClient: Sync + Send {
17    type HeaderName: Clone + Sync + Send;
18    type Error: Debug + Display + Error + Send + Sync + 'static;
19    type RequestBuilder;
20
21    /// Construct a HTTP client layer headername
22    fn build_header(name: &'static str) -> Result<Self::HeaderName, Self::Error>;
23
24    /// Make a get request
25    fn get(&self, uri: &str) -> Self::RequestBuilder;
26
27    /// Make a post  request
28    fn post(&self, uri: &str) -> Self::RequestBuilder;
29
30    /// Add a header to a request
31    fn header(
32        builder: Self::RequestBuilder,
33        key: &Self::HeaderName,
34        value: &str,
35    ) -> Self::RequestBuilder;
36
37    /// Make a get request and parse into JSON
38    async fn get_json<T: DeserializeOwned>(req: Self::RequestBuilder) -> Result<T, Self::Error>;
39
40    /// Encode content into JSON and post to an endpoint. Returns the statuscode
41    /// is_success() value.
42    async fn post_json<T: Serialize + Sync>(
43        req: Self::RequestBuilder,
44        content: &T,
45    ) -> Result<bool, Self::Error>;
46}