1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
//! Contains the `Request` class, used for building requests to the API.

use reqwest::blocking::{
    RequestBuilder
};

#[cfg(feature = "async")]
use reqwest::{
    RequestBuilder as ARequestBuilder
};

use reqwest::{
    header::{
        HeaderMap,
        USER_AGENT, AUTHORIZATION, CONTENT_TYPE, CONTENT_LENGTH,
        HeaderValue,
    },
    Url,
    Method,
};
use crate::error::{Result, Error};
use crate::http::Client;
use crate::constants::USER_AGENT as B_API_USER_AGENT;


/// A struct representing a request to some endpoint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request<'a> {

    /// The body of the request. (Note that this is rarely, if ever, used in this lib.)
    pub body: Option<&'a [u8]>,

    /// The headers of the request.
    pub headers: Option<HeaderMap>,

    /// The endpoint (e.g. /players/%23sometag).
    pub endpoint: String,

    /// The method (GET/POST/...). Defaults to GET
    pub method: Method,
}

impl<'a> Default for Request<'a> {
    /// Returns a default `Request` instance, with initial values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use brawl_api::http::request::Request;
    /// use reqwest::Method;
    ///
    /// assert_eq!(
    ///     Request::default(),
    ///     Request {
    ///         body: None,
    ///         headers: None,
    ///         endpoint: String::from(""),
    ///         method: Method::GET,
    ///     }
    /// )
    /// ```
    fn default() -> Request<'a> {
        Request {
            body: None,
            headers: None,
            endpoint: String::from(""),
            method: Method::GET,
        }
    }
}

// (Credits to Serenity lib for the useful HTTP bases)
impl<'a> Request<'a> {
    /// (For sync usage) Creates a (blocking) [`RequestBuilder`] (`reqwest` crate) instance.
    ///
    /// [`RequestBuilder`]: https://docs.rs/reqwest/*/reqwest/blocking/struct.RequestBuilder.html
    pub fn build(&'a self, client: &Client) -> Result<RequestBuilder> {
        let Request {
            body,
            headers: ref r_headers,
            endpoint: ref r_endpoint,
            ref method,
        } = *self;

        let mut builder = client.inner.request(
            method.clone(),
            Url::parse(r_endpoint).map_err(Error::Url)?,
        );

        if let Some(ref bytes) = body {  // body was provided
            let b_vec = Vec::from(*bytes);
            builder = builder.body(b_vec);
        }

        let key = &client.auth_key;

        let key = if key.starts_with("Bearer ") {
            key.clone()
        } else {
            format!("Bearer {}", key)
        };

        let mut headers = HeaderMap::with_capacity(3);
        headers.insert(USER_AGENT, HeaderValue::from_static(&B_API_USER_AGENT));
        headers.insert(AUTHORIZATION,
                       HeaderValue::from_str(&key).map_err(Error::Authorization)?);
        headers.insert(CONTENT_TYPE, HeaderValue::from_static(&"application/json"));
        headers.insert(CONTENT_LENGTH, HeaderValue::from_static(&"0"));

        if let Some(ref r_headers) = r_headers {
            headers.extend(r_headers.clone());
        }

        builder = builder.headers(headers);

        Ok(builder)
    }

    /// (For async usage) Creates a (non-blocking) [`RequestBuilder`] (`reqwest` crate) instance.
    ///
    /// [`RequestBuilder`]: https://docs.rs/reqwest/*/reqwest/struct.RequestBuilder.html
    #[cfg(feature = "async")]
    pub fn a_build(&'a self, client: &Client) -> Result<ARequestBuilder> {
        let Request {
            body,
            headers: ref r_headers,
            endpoint: ref r_endpoint,
            ref method,
        } = *self;

        let mut builder = client.a_inner.request(
            method.clone(),
            Url::parse(r_endpoint).map_err(Error::Url)?,
        );

        if let Some(ref bytes) = body {  // body was provided
            let b_vec = Vec::from(*bytes);
            builder = builder.body(b_vec);
        }

        let key = &client.auth_key;

        let key = if key.starts_with("Bearer ") {
            key.clone()
        } else {
            format!("Bearer {}", key)  // add "Bearer " if missing.
        };

        let mut headers = HeaderMap::with_capacity(3);
        headers.insert(USER_AGENT, HeaderValue::from_static(&B_API_USER_AGENT));
        headers.insert(AUTHORIZATION,
                       HeaderValue::from_str(&key).map_err(Error::Authorization)?);
        headers.insert(CONTENT_TYPE, HeaderValue::from_static(&"application/json"));
        headers.insert(CONTENT_LENGTH, HeaderValue::from_static(&"0"));

        if let Some(ref r_headers) = r_headers {
            headers.extend(r_headers.clone());
        }

        builder = builder.headers(headers);

        Ok(builder)
    }
}