pinboard_rs/api/
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
7use std::borrow::Cow;
8
9use http::{self, header, Method, Request};
10use serde::de::DeserializeOwned;
11
12use crate::api::{query, ApiError, BodyError, Client, Query, QueryParams};
13
14/// A trait for providing the necessary informatino for a single REST API endpoint.
15pub trait Endpoint {
16    /// The HTTP method to use for the endpoint
17    fn method(&self) -> Method;
18    /// The path to the endpoint.
19    fn endpoint(&self) -> Cow<'static, str>;
20
21    /// Query parameters for the endpoint.
22    fn parameters(&self) -> QueryParams {
23        QueryParams::default()
24    }
25
26    /// The body for the Endpoint
27    ///
28    /// Returns the `Content-Encoding` header and the data itself
29    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
30        Ok(None)
31    }
32}
33
34impl<E, T, C> Query<T, C> for E
35where
36    E: Endpoint,
37    T: DeserializeOwned,
38    C: Client,
39{
40    fn query(&self, client: &C) -> Result<T, ApiError<C::Error>> {
41        let mut url = client.rest_endpoint(&self.endpoint())?;
42        self.parameters().add_to_url(&mut url);
43
44        let req = Request::builder()
45            .method(self.method())
46            .uri(query::url_to_http_uri(url));
47        let (req, data) = if let Some((mime, data)) = self.body()? {
48            let req = req.header(header::CONTENT_TYPE, mime);
49            (req, data)
50        } else {
51            (req, Vec::new())
52        };
53        let rsp = client.rest(req, data)?;
54        let status = rsp.status();
55        let v = serde_json::from_slice(rsp.body())?;
56        if !status.is_success() {
57            return Err(ApiError::from_pinboard(v));
58        }
59
60        serde_json::from_value::<T>(v).map_err(ApiError::data_type::<T>)
61    }
62}