1use serde::{Deserialize, Serialize};
2use std::fmt::Display;
3
4#[derive(Debug, Serialize, Deserialize, Clone)]
5pub struct UtRequest {
6 pub slug: String,
7 pub action_type: String,
8 pub file_name: String,
9 pub file_size: u64,
10}
11impl Into<web_sys::RequestInit> for UtRequest {
12 fn into(self) -> web_sys::RequestInit {
13 let opts = web_sys::RequestInit::new();
14 opts.set_method("POST");
15 opts.set_mode(web_sys::RequestMode::Cors);
16 opts.set_body(&web_sys::wasm_bindgen::JsValue::from_str(
17 self.to_string().as_str(),
18 ));
19 let headers = web_sys::Headers::new().expect("Failed to build headers");
20 headers
21 .set("Content-Type", "application/json")
22 .expect("Failed to set header");
23 opts.set_headers(&headers);
24 opts
25 }
26}
27impl From<&web_sys::File> for UtRequest {
28 fn from(file: &web_sys::File) -> Self {
29 let slug = file
30 .name()
31 .to_lowercase()
32 .replace(" ", "-")
33 .replace(".", "-");
34 Self {
35 slug,
36 action_type: "upload".to_string(),
37 file_name: file.name(),
38 file_size: file.size().abs() as u64,
39 }
40 }
41}
42impl From<web_sys::File> for UtRequest {
43 fn from(file: web_sys::File) -> Self {
44 let slug = file
45 .name()
46 .to_lowercase()
47 .replace(" ", "-")
48 .replace(".", "-");
49 Self {
50 slug,
51 action_type: "upload".to_string(),
52 file_name: file.name(),
53 file_size: file.size().abs() as u64,
54 }
55 }
56}
57impl TryFrom<String> for UtRequest {
58 type Error = anyhow::Error;
59 fn try_from(value: String) -> Result<Self, Self::Error> {
60 let presigned_url: Self = serde_json::from_str(&value)?;
61 Ok(presigned_url)
62 }
63}
64impl TryFrom<&web_sys::wasm_bindgen::JsValue> for UtRequest {
65 type Error = web_sys::wasm_bindgen::JsValue;
66 fn try_from(value: &web_sys::wasm_bindgen::JsValue) -> Result<Self, Self::Error> {
67 let js_str = web_sys::js_sys::JSON::stringify(value)?;
68 let str = js_str
69 .as_string()
70 .ok_or_else(|| web_sys::wasm_bindgen::JsValue::from_str("Failed to stringify JSON"))?;
71 let presigned_url: Self = serde_json::from_str(&str).map_err(|e| {
72 web_sys::wasm_bindgen::JsValue::from_str(&format!("Failed to parse JSON: {}", e))
73 })?;
74 Ok(presigned_url)
75 }
76}
77impl TryFrom<web_sys::wasm_bindgen::JsValue> for UtRequest {
78 type Error = web_sys::wasm_bindgen::JsValue;
79 fn try_from(value: web_sys::wasm_bindgen::JsValue) -> Result<Self, Self::Error> {
80 Self::try_from(&value)
81 }
82}
83
84impl Default for UtRequest {
85 fn default() -> Self {
86 Self {
87 slug: "".to_string(),
88 action_type: "upload".to_string(),
89 file_name: "".to_string(),
90 file_size: 0,
91 }
92 }
93}
94impl Display for UtRequest {
95 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 write!(f, "{}", serde_json::to_string(&self).unwrap())
97 }
98}