rust_fetch/
fetch_options.rs1use crate::FetchHeaders;
2use std::str::FromStr;
3use std::{collections::HashMap, fmt::Display};
4
5#[derive(Debug, Clone)]
6pub struct FetchOptions {
7 pub headers: Option<FetchHeaders>,
8 pub accept: Option<ContentType>,
9 pub content_type: Option<ContentType>,
10 pub params: Option<HashMap<String, String>>,
11 pub deserialize_body: bool,
12}
13
14impl Default for FetchOptions {
15 fn default() -> Self {
16 Self {
17 headers: Default::default(),
18 params: Default::default(),
19 accept: Default::default(),
20 content_type: Default::default(),
21 deserialize_body: true,
22 }
23 }
24}
25
26#[derive(Debug, Clone)]
27pub enum ContentType {
29 Json,
31 TextXml,
33 ApplicationXml,
35 UrlEncoded,
37}
38
39impl FromStr for ContentType {
40 type Err = ();
41
42 fn from_str(s: &str) -> Result<Self, Self::Err> {
43 return match s {
44 "application/json" => Ok(Self::Json),
45 "text/xml" => Ok(Self::TextXml),
46 "application/xml" => Ok(Self::ApplicationXml),
47 "application/x-www-form-urlencoded" => Ok(Self::UrlEncoded),
48 _ => Err(()),
49 };
50 }
51}
52
53impl From<ContentType> for String {
54 fn from(content_type: ContentType) -> Self {
55 format!("{content_type}")
56 }
57}
58
59impl Display for ContentType {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 match self {
62 ContentType::Json => write!(f, "application/json"),
63 ContentType::TextXml => write!(f, "text/xml"),
64 ContentType::ApplicationXml => write!(f, "application/xml"),
65 ContentType::UrlEncoded => write!(f, "application/x-www-form-urlencoded"),
66 }
67 }
68}
69
70impl Default for ContentType {
71 fn default() -> Self {
72 Self::Json
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::ContentType;
79
80 #[test]
81 fn test_content_type_json_to_string() {
82 let c_type = ContentType::Json;
83 assert_eq!(String::from("application/json"), String::from(c_type));
84 }
85
86 #[test]
87 fn test_content_type_application_xml_to_string() {
88 let c_type = ContentType::ApplicationXml;
89 assert_eq!(String::from("application/xml"), String::from(c_type));
90 }
91
92 #[test]
93 fn test_content_type_text_xml_to_string() {
94 let c_type = ContentType::TextXml;
95 assert_eq!(String::from("text/xml"), String::from(c_type));
96 }
97
98 #[test]
99 fn test_content_type_url_encoded_to_string() {
100 let c_type = ContentType::UrlEncoded;
101 assert_eq!(
102 String::from("application/x-www-form-urlencoded"),
103 String::from(c_type)
104 );
105 }
106}