paystack/
utils.rs

1//! Utils
2//! ============
3//! This file contains utility sections that are used in different sections of the client
4
5use reqwest::{Client, Error, Response};
6use serde::Serialize;
7use std::fmt::Debug;
8
9/// A function for sending GET request to a specified url
10/// with optional query parameters using reqwest client.
11pub async fn get_request(
12    api_key: &str,
13    url: &str,
14    query: Option<Vec<(&str, &str)>>,
15) -> Result<Response, Error> {
16    let client = Client::new();
17    let response = client
18        .get(url)
19        .query(&query)
20        .bearer_auth(api_key)
21        .header("Content-Type", "application/json")
22        .send()
23        .await;
24
25    match response {
26        Ok(response) => Ok(response),
27        Err(err) => Err(err),
28    }
29}
30
31/// A function for sending POST requests to a specified url
32/// using the reqwest client.
33pub async fn post_request<T>(api_key: &str, url: &str, body: T) -> Result<Response, Error>
34where
35    T: Debug + Serialize,
36{
37    let client = Client::new();
38    let response = client
39        .post(url)
40        .bearer_auth(api_key)
41        .header("Content-Type", "application/json")
42        .json(&body)
43        .send()
44        .await;
45
46    match response {
47        Ok(response) => Ok(response),
48        Err(err) => Err(err),
49    }
50}
51
52/// A function for sending PUT requests to a specified url
53/// using the reqwest client.
54pub async fn put_request<T>(api_key: &str, url: &str, body: T) -> Result<Response, Error>
55where
56    T: Debug + Serialize,
57{
58    let client = Client::new();
59    let response = client
60        .put(url)
61        .bearer_auth(api_key)
62        .header("Content-Type", "application/json")
63        .json(&body)
64        .send()
65        .await;
66
67    match response {
68        Ok(response) => Ok(response),
69        Err(err) => Err(err),
70    }
71}
72
73/// A function for sending DELETE requests to a specified url
74/// using the reqwest client.
75pub async fn delete_request<T>(api_key: &str, url: &str, body: T) -> Result<Response, Error>
76where
77    T: Debug + Serialize,
78{
79    let client = Client::new();
80    let response = client
81        .delete(url)
82        .bearer_auth(api_key)
83        .header("Content-Type", "application/json")
84        .json(&body)
85        .send()
86        .await;
87
88    match response {
89        Ok(response) => Ok(response),
90        Err(err) => Err(err),
91    }
92}