nutt_web/http/
request.rs

1use crate::http::cookie::CookieJar;
2use crate::http::method::Method;
3use crate::http::HttpBody;
4use crate::modules::session::Session;
5use serde::de::DeserializeOwned;
6use serde::{Deserialize, Serialize};
7use serde_json::Error;
8use std::any::Any;
9use std::collections::HashMap;
10use std::sync::{Arc, RwLock, RwLockReadGuard};
11
12#[derive(Debug)]
13pub struct Request {
14    method: Method,
15    session: Arc<Option<Session>>,
16    states: Arc<RwLock<HashMap<String, Box<dyn Any + Send + Sync>>>>,
17    body: HttpBody,
18    cookie_jar: CookieJar,
19}
20
21impl Request {
22    pub(crate) fn set_states(
23        &mut self,
24        states: Arc<RwLock<HashMap<String, Box<dyn Any + Send + Sync>>>>,
25    ) {
26        self.states = states;
27    }
28    pub(crate) fn set_session(&mut self, session: Arc<Option<Session>>) {
29        self.session = session;
30    }
31
32    pub(crate) fn set_cookie_jar(&mut self, cookie_jar: CookieJar) {
33        self.cookie_jar = cookie_jar
34    }
35}
36
37impl Request {
38    pub fn body_json<T: for<'a> Deserialize<'a> + DeserializeOwned>(&self) -> Result<T, Error> {
39        serde_json::from_str::<T>(self.body.body.as_str().unwrap())
40    }
41
42    pub fn get_state(&self) -> RwLockReadGuard<'_, HashMap<String, Box<dyn Any + Send + Sync>>> {
43        self.states.try_read().unwrap()
44    }
45
46    pub fn get_session(&self) -> Arc<Option<Session>> {
47        self.session.clone()
48    }
49    pub fn get_method(&self) -> Method {
50        self.method.clone()
51    }
52
53    pub fn get_cookie_jar(&self) -> CookieJar {
54        self.cookie_jar.clone()
55    }
56}
57
58pub struct RequestBuilder {
59    method: Method,
60    body: HttpBody,
61    states: HashMap<String, Box<dyn Any + Send + Sync>>,
62    session: Option<Session>,
63    cookie_jar: CookieJar,
64}
65
66impl RequestBuilder {
67    pub fn new<T: Serialize + Clone + Send>(method: Method, body: T) -> Self {
68        Self {
69            method,
70            body: HttpBody::new(serde_json::to_value(body).unwrap()),
71            states: HashMap::new(),
72            session: None,
73            cookie_jar: CookieJar::new(),
74        }
75    }
76
77    pub(crate) fn set_cookie_jar(mut self, cookie_jar: CookieJar) -> Self {
78        self.cookie_jar = cookie_jar;
79        self
80    }
81
82    pub fn build(self) -> Request {
83        Request {
84            method: self.method,
85            body: self.body,
86            states: Arc::new(RwLock::new(self.states)),
87            session: Arc::new(self.session),
88            cookie_jar: self.cookie_jar,
89        }
90    }
91}