Skip to main content

rumtk_web/utils/
form_data.rs

1/*
2 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 * This toolkit aims to be reliable, simple, performant, and standards compliant.
4 * Copyright (C) 2025  Luis M. Santos, M.D.
5 * Copyright (C) 2025  Nick Stephenson
6 * Copyright (C) 2025  Ethan Dixon
7 * Copyright (C) 2025  MedicalMasses L.L.C.
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
22 */
23use 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}