gen_api_wrapper/
endpoint.rs

1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6//
7// Originally from https://gitlab.kitware.com/utils/rust-gitlab
8//
9// Modified in an attempt to make it general beyond just gitlab
10
11use std::borrow::Cow;
12
13use http::{self, header, Method, Request};
14use serde::de::DeserializeOwned;
15
16use crate::{
17    client::{AsyncClient, Client},
18    error::{ApiError, BodyError},
19    params::QueryParams,
20    query::{self, AsyncQuery, Query},
21};
22
23/// A trait for providing the necessary information for a single REST API endpoint.
24pub trait Endpoint {
25    /// The HTTP method to use for the endpoint.
26    fn method(&self) -> Method;
27    /// The path to the endpoint.
28    fn endpoint(&self) -> Cow<'static, str>;
29
30    /// Query parameters for the endpoint.
31    fn parameters(&self) -> QueryParams<'_> {
32        QueryParams::default()
33    }
34
35    /// The body for the endpoint.
36    ///
37    /// Returns the `Content-Encoding` header for the data as well as the data itself.
38    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
39        Ok(None)
40    }
41}
42
43impl<E, T, C> Query<T, C> for E
44where
45    E: Endpoint,
46    T: DeserializeOwned,
47    C: Client,
48{
49    fn query(&self, client: &C) -> Result<T, ApiError<C::Error>> {
50        let mut url = client.rest_endpoint(&self.endpoint())?;
51        self.parameters().add_to_url(&mut url);
52
53        let req = Request::builder()
54            .method(self.method())
55            .uri(query::url_to_http_uri(url));
56        let (req, data) = if let Some((mime, data)) = self.body()? {
57            let req = req.header(header::CONTENT_TYPE, mime);
58            (req, data)
59        } else {
60            (req, Vec::new())
61        };
62        let rsp = client.rest(req, data)?;
63        let status = rsp.status();
64        let v = if let Ok(v) = serde_json::from_slice(rsp.body()) {
65            v
66        } else {
67            return Err(ApiError::server_error(status, rsp.body()));
68        };
69        if !status.is_success() {
70            return Err(ApiError::server_error(status, rsp.body()));
71        }
72
73        serde_json::from_value::<T>(v).map_err(ApiError::data_type::<T>)
74    }
75}
76
77impl<E, T, C> AsyncQuery<T, C> for E
78where
79    E: Endpoint + Sync,
80    T: DeserializeOwned + 'static,
81    C: AsyncClient + Sync,
82{
83    async fn query_async(&self, client: &C) -> Result<T, ApiError<C::Error>> {
84        let mut url = client.rest_endpoint(&self.endpoint())?;
85        self.parameters().add_to_url(&mut url);
86
87        let req = Request::builder()
88            .method(self.method())
89            .uri(query::url_to_http_uri(url));
90        let (req, data) = if let Some((mime, data)) = self.body()? {
91            let req = req.header(header::CONTENT_TYPE, mime);
92            (req, data)
93        } else {
94            (req, Vec::new())
95        };
96        let rsp = client.rest_async(req, data).await?;
97        let status = rsp.status();
98        let v = if let Ok(v) = serde_json::from_slice(rsp.body()) {
99            v
100        } else {
101            return Err(ApiError::server_error(status, rsp.body()));
102        };
103        if !status.is_success() {
104            return Err(ApiError::server_error(status, rsp.body()));
105        }
106
107        serde_json::from_value::<T>(v).map_err(ApiError::data_type::<T>)
108    }
109}