rumtk_web/utils/
form_data.rs1use rumtk_core::core::RUMResult;
24use rumtk_core::strings::{
25 rumtk_format, RUMArrayConversions, RUMString, RUMStringConversions, ToCompactString,
26};
27use rumtk_core::types::{RUMBuffer, RUMHashMap, RUMID};
28
29use crate::utils::defaults::*;
30use crate::{RUMWebData, RouterForm};
31
32pub type FormBuffer = RUMBuffer;
33
34#[derive(Default, Debug)]
35pub struct FormData {
36 pub form: RUMWebData,
37 pub files: RUMHashMap<RUMString, FormBuffer>,
38}
39
40pub type FormResult = RUMResult<FormData>;
41
42pub async fn get_type(content_type: &str) -> &'static str {
43 match content_type {
44 CONTENT_TYPE_PDF => FORM_DATA_TYPE_PDF,
45 _ => FORM_DATA_TYPE_DEFAULT,
46 }
47}
48
49pub async fn compile_form_data(form: &mut RouterForm) -> FormResult {
50 let mut form_data = FormData::default();
51
52 while let Some(mut field) = form.next_field().await.unwrap() {
53 let typ = match field.content_type() {
54 Some(content_type) => get_type(content_type).await,
55 None => FORM_DATA_TYPE_DEFAULT,
56 };
57 let name = field.name().unwrap_or_default().to_rumstring();
58
59 let data = match field.bytes().await {
60 Ok(bytes) => bytes,
61 Err(e) => return Err(rumtk_format!("Field data transfer failed because {}!", e)),
62 };
63
64 if typ == FORM_DATA_TYPE_DEFAULT {
65 form_data.form.insert(name, data.to_vec().to_rumstring());
66 } else {
67 let file_id = RUMID::new_v4().to_compact_string();
68 &form_data.files.insert(file_id.clone(), data);
69 &form_data.form.insert(name, file_id);
70 }
71 }
72
73 Ok(form_data)
74}