Skip to main content

infinispan_fork/request/
mod.rs

1use std::collections::HashMap;
2
3use http::header::CONTENT_TYPE;
4use http::Request as HttpRequest;
5
6pub mod caches;
7pub mod counters;
8pub mod entries;
9
10#[derive(Debug)]
11pub enum Method {
12    Get,
13    Head,
14    Post,
15    Put,
16    Delete,
17}
18
19impl Method {
20    pub const fn as_str(&self) -> &str {
21        use Method::*;
22
23        match self {
24            Get => "GET",
25            Head => "HEAD",
26            Post => "POST",
27            Put => "PUT",
28            Delete => "DELETE",
29        }
30    }
31}
32
33#[derive(Debug)]
34pub struct Request {
35    pub method: Method,
36    pub path_and_query: String,
37    pub headers: HashMap<String, String>,
38    pub body: Option<String>,
39}
40
41pub trait ToHttpRequest {
42    fn to_http_req(&self, base_url: impl AsRef<str>) -> HttpRequest<String>;
43}
44
45impl Request {
46    pub fn new(
47        method: impl Into<Method>,
48        path_and_query: impl Into<String>,
49        headers: HashMap<String, String>,
50        body: Option<String>,
51    ) -> Self {
52        Self {
53            method: method.into(),
54            path_and_query: path_and_query.into(),
55            headers,
56            body,
57        }
58    }
59}
60
61impl ToHttpRequest for Request {
62    fn to_http_req(&self, base_url: impl AsRef<str>) -> HttpRequest<String> {
63        let mut http_req = HttpRequest::builder()
64            .method(self.method.as_str())
65            .uri(format!("{}{}", base_url.as_ref(), self.path_and_query));
66
67        http_req = http_req.header(CONTENT_TYPE, "application/json");
68
69        println!("{:?}", self.headers);
70        for (header_name, header_val) in &self.headers {
71            http_req = http_req.header(header_name.as_str(), header_val);
72        }
73
74        http_req
75            .body(
76                self.body
77                    .as_ref()
78                    .map_or_else(Default::default, ToString::to_string),
79            )
80            .unwrap()
81    }
82}