fusen_rs/protocol/fusen/
request.rs1use crate::error::FusenError;
2use fusen_internal_common::protocol::Protocol;
3use http::Method;
4use serde_json::Value;
5use std::{
6 collections::{HashMap, LinkedList},
7 str::FromStr,
8};
9
10#[derive(Debug)]
11pub struct Path {
12 pub method: Method,
13 pub path: String,
14}
15
16#[derive(Debug)]
17pub struct FusenRequest {
18 pub protocol: Protocol,
19 pub path: Path,
20 pub addr: Option<String>,
21 pub querys: HashMap<String, String>,
22 pub headers: HashMap<String, String>,
23 pub extensions: Option<HashMap<String, String>>,
24 pub bodys: Option<LinkedList<Value>>,
25}
26
27impl FusenRequest {
28 pub fn get_bodys(&mut self, fields: &[(&str, &str)]) -> Result<LinkedList<Value>, FusenError> {
29 let mut bodys = LinkedList::new();
30 if let Method::POST = self.path.method {
31 return Ok(self.bodys.take().unwrap_or_default());
32 }
33 for (field_name, field_type) in fields {
34 let field_name = if let Some(field_name) = field_name.strip_prefix("r#") {
35 field_name
36 } else {
37 field_name
38 };
39 let value = match self.querys.get(field_name) {
40 Some(value) => {
41 let result = if *field_type == "String" || *field_type == "Option < String >" {
42 serde_json::from_str(&format!("{value:?}"))
43 } else {
44 serde_json::from_str(value)
45 };
46 result.map_err(|error| FusenError::Error(Box::new(error)))?
47 }
48 None => Value::Null,
49 };
50 bodys.push_back(value);
51 }
52 Ok(bodys)
53 }
54
55 pub fn init_request(
56 protocol: Protocol,
57 method: &str,
58 path: &str,
59 field_pats: &[&str],
60 mut request_bodys: LinkedList<Value>,
61 ) -> Result<Self, FusenError> {
62 let method =
63 Method::from_str(method).map_err(|error| FusenError::Error(Box::new(error)))?;
64 let mut bodys = None;
65 let mut querys = HashMap::new();
66 if let Method::POST = method {
67 let _ = bodys.insert(request_bodys);
68 } else {
69 for field_pat in field_pats.iter().rev() {
70 let field_name = if let Some(field_pat) = field_pat.strip_prefix("r#") {
71 field_pat
72 } else {
73 field_pat
74 };
75 let value = request_bodys.pop_back().ok_or(FusenError::Impossible)?;
76 if value.is_null() {
77 continue;
78 }
79 let mut query_value = value.to_string();
80 if value.is_string() {
81 query_value = query_value[1..query_value.len() - 1].to_string();
82 }
83 querys.insert(field_name.to_owned(), query_value);
84 }
85 }
86 Ok(Self {
87 protocol,
88 path: Path {
89 method,
90 path: path.to_owned(),
91 },
92 addr: None,
93 querys,
94 headers: Default::default(),
95 extensions: Default::default(),
96 bodys,
97 })
98 }
99}