Struct Fetch

Source
pub struct Fetch {
    pub config: Option<FetchConfig>,
    /* private fields */
}

Fields§

§config: Option<FetchConfig>

Implementations§

Source§

impl Fetch

Source

pub fn new(base_url: &str, options: Option<FetchConfig>) -> FetchResult<Self>

Creates a new instance of Fetch with a set base url and optional Options

§Example
use rust_fetch::Fetch;
let client = Fetch::new("http://localhost", None);
assert_ne!(true, client.is_err());
Source

pub fn set_default_headers( &mut self, headers: Option<FetchHeaders>, ) -> FetchResult<()>

Sets the default headers for this instance of Fetch.

§Example
use rust_fetch::{Fetch, map_string};

let mut client = Fetch::new("http://localhost", None).unwrap();
let set_header_result = client.set_default_headers(Some(map_string!{ header1 : "header 1 value" }));
assert_ne!(true, set_header_result.is_err());
Source

pub fn build_url( &self, endpoint: &str, options: Option<&FetchOptions>, ) -> FetchResult<Url>

Source

pub async fn post<T, U>( &self, endpoint: &str, data: Option<U>, options: Option<FetchOptions>, ) -> FetchResult<FetchResponse<T>>
where T: for<'de> Deserialize<'de>, U: Serialize,

Sends an HTTP Post request to the configured remote server

  • endpoint - The remote endpoint. This gets joined with the base_url configured in the ::new() method
  • data - Optional data to send to the remote endpoint (to be serialized as JSON). If None, then no data is sent instead of null
  • options - The FetchOptions for this call. Allows setting of headers and/or query params
§Example
use httpmock::prelude::*;
use rust_fetch::Fetch;

#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
struct ToReturn {}

#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct ToSend {
    test_key: String,
}

#[tokio::main]
async fn main() {
    let server = MockServer::start();

    server.mock(|when, then| {
        when.path("/test").method(POST);
        then.status(200).json_body(serde_json::json!({}));
    });

    let fetch = Fetch::new(&server.base_url(), None).unwrap();

     let response = fetch
        .post::<ToReturn, ToSend>(
            "/test",
            Some(ToSend {
                test_key: "Testing".to_string(),
            }),
            Some(rust_fetch::FetchOptions {
                params: Some(rust_fetch::map_string! {param1 : "value1"}),
                ..Default::default()
            }),
        )
        .await.unwrap();
    assert_eq!(&200, &response.status);
    assert_eq!(ToReturn {}, response.body.unwrap());
}
Source

pub async fn get<T>( &self, endpoint: &str, options: Option<FetchOptions>, ) -> FetchResult<FetchResponse<T>>
where T: for<'de> Deserialize<'de>,

Sends an HTTP GET request to the configured remote server

  • endpoint - The remote endpoint. This gets joined with the base_url configured in the ::new() method
  • options - The FetchOptions for this call. Allows setting of headers and/or query params
§Example
    use rust_fetch::Fetch;
    use httpmock::prelude::*;

    #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
    struct ToReturn {
         
    }

    #[tokio::main]
    async fn main() {
        let server = MockServer::start();
         
        server.mock(|when, then|{
            when.path("/test");
            then.status(200).json_body(serde_json::json!({}));
        });

        let fetch = Fetch::new(&server.base_url(), None).unwrap();

        let response = fetch.get::<ToReturn>("/test", Some(rust_fetch::FetchOptions
        {
            params: Some(rust_fetch::map_string!{param1 : "value1"}),
            ..Default::default()
        })).await.unwrap();
        assert_eq!(&200, &response.status);
        assert_eq!(ToReturn{}, response.body.unwrap());
    }
     
Source

pub async fn delete<T, U>( &self, endpoint: &str, data: Option<T>, options: Option<FetchOptions>, ) -> FetchResult<FetchResponse<U>>
where T: Serialize, U: for<'de> Deserialize<'de>,

Sends an HTTP DELETE request to the configured remote server

  • endpoint - The remote endpoint. This gets joined with the base_url configured in the ::new() method
  • data - The optional data to send the the remote endpoint
  • options - The FetchOptions for this call. Allows setting of headers and/or query params
§Example
    use rust_fetch::Fetch;
    use httpmock::prelude::*;

    #[derive(serde::Deserialize, Debug, PartialEq)]
    struct ToReturn {}

    #[tokio::main]
    async fn main() {
        let server = MockServer::start();

        server.mock(| when, then | {
            when.path("/test").method(DELETE);
            then.status(200).json_body(serde_json::json!({}));
        });

        let client = Fetch::new(&server.base_url(), None).unwrap();

        let res = client.delete::<(), ToReturn>("/test", None, None).await.unwrap();
        assert_eq!(&200, &res.status);
        assert_eq!(ToReturn {}, res.body.unwrap());
    }
Source

pub async fn put<T, U>( &self, endpoint: &str, data: Option<T>, options: Option<FetchOptions>, ) -> FetchResult<FetchResponse<U>>
where T: Serialize, U: for<'de> Deserialize<'de>,

Sends an HTTP PUT request to the configured remote server

  • endpoint - The remote endpoint. This gets joined with the base_url configured in the ::new() method
  • data - The optional data to send the the remote endpoint
  • options - The FetchOptions for this call. Allows setting of headers and/or query params
§Example
    use rust_fetch::Fetch;
    use httpmock::prelude::*;

    #[derive(serde::Deserialize, Debug, PartialEq)]
    struct ToReturn {}

    #[tokio::main]
    async fn main() {
        let server = MockServer::start();

        server.mock(| when, then | {
            when.path("/test").method(PUT);
            then.status(200).json_body(serde_json::json!({}));
        });

        let client = Fetch::new(&server.base_url(), None).unwrap();

        let res = client.put::<(), ToReturn>("/test", None, None).await.unwrap();
        assert_eq!(&200, &res.status);
        assert_eq!(ToReturn {}, res.body.unwrap());
    }
Source

pub async fn patch<T, U>( &self, endpoint: &str, data: Option<T>, options: Option<FetchOptions>, ) -> FetchResult<FetchResponse<U>>
where T: Serialize, U: for<'de> Deserialize<'de>,

Sends an HTTP PATCH request to the configured remote server

  • endpoint - The remote endpoint. This gets joined with the base_url configured in the ::new() method
  • data - The optional data to send the the remote endpoint
  • options - The FetchOptions for this call. Allows setting of headers and/or query params
§Example
    use rust_fetch::Fetch;
    use httpmock::prelude::*;

    #[derive(serde::Deserialize, Debug, PartialEq)]
    struct ToReturn {}

    #[tokio::main]
    async fn main() {
        let server = MockServer::start();

        server.mock(| when, then | {
            when.path("/test").method(httpmock::Method::PATCH);
            then.status(200).json_body(serde_json::json!({}));
        });

        let client = Fetch::new(&server.base_url(), None).unwrap();

        let res = client.patch::<(), ToReturn>("/test", None, None).await.unwrap();
        assert_eq!(&200, &res.status);
        assert_eq!(ToReturn {}, res.body.unwrap());
    }

Trait Implementations§

Source§

impl Debug for Fetch

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Fetch

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for Fetch

§

impl !RefUnwindSafe for Fetch

§

impl Send for Fetch

§

impl Sync for Fetch

§

impl Unpin for Fetch

§

impl !UnwindSafe for Fetch

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,