rrw 0.1.2

A crate to easily build clients for REST-APIs.
Documentation
use serde::Serialize;

/// A request to a REST-API.
///
/// # Examples
///
/// A simple GET-request with no attached data.
///
/// ```rust
/// # use std::error::Error;
/// # use rrw::RestRequest;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let request = RestRequest::<(), ()>::get("/get-endpoint");
/// #
/// #     Ok(())
/// # }
/// ```
///
/// A POST-request with a body.
///
/// ```rust
/// # use std::error::Error;
/// use rrw::RestRequest;
/// use serde::Serialize;
///
///#[derive(Serialize)]
/// struct Body {
///     key: String
/// }
///
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let body = Body {
///     key: "value".to_string()
/// };
/// let request = RestRequest::<(), &Body>::post("/post-endpoint").body(&body);
/// #
/// #     Ok(())
/// # }
/// ```

pub struct RestRequest<Q, B> {
    pub(crate) method: reqwest::Method,
    pub(crate) path: String,
    pub(crate) query: Option<Q>,
    pub(crate) body: Option<B>,
    pub(crate) authenticate: bool,
}

impl<Q, B> RestRequest<Q, B>
where
    Q: Serialize,
    B: Serialize,
{
    /// Construct a [RestRequest] using the given path and request method.
    ///
    /// This will leave the query and body of the request empty. This will also not be
    /// authenticated.
    ///
    /// Look at [RestRequest::get], [RestRequest::post] and similar for easier constructors.
    pub fn with_method<S: AsRef<str>>(path: S, method: reqwest::Method) -> Self {
        log::trace!(
            "Create new RestRequest for endpoint {} with method {}.",
            path.as_ref(),
            method
        );
        Self {
            method,
            path: path.as_ref().to_string(),
            query: None,
            body: None,
            authenticate: false,
        }
    }

    /// Construct a GET [RestRequest] using the given path.
    ///
    /// For more information, see [RestRequest::with_method].
    pub fn get<S: AsRef<str>>(path: S) -> Self {
        Self::with_method(path, reqwest::Method::GET)
    }

    /// Construct a POST [RestRequest] using the given path.
    ///
    /// For more information, see [RestRequest::with_method].
    pub fn post<S: AsRef<str>>(path: S) -> Self {
        Self::with_method(path, reqwest::Method::POST)
    }

    /// Set the query (url-parameters) of the request.
    pub fn query(mut self, query: Q) -> Self {
        self.query = Some(query);
        self
    }

    /// Set the body of the request.
    pub fn body(mut self, body: B) -> Self {
        self.body = Some(body);
        self
    }

    /// Mark this request as needing to be authenticated.
    pub fn authenticate(mut self) -> Self {
        self.authenticate = true;
        self
    }
}