From 064935feb1298b047a407384c09f1c1748162f8d Mon Sep 17 00:00:00 2001 From: Mo8it Date: Sat, 25 Feb 2023 21:14:58 +0100 Subject: [PATCH] Rename id to key and refactor from_map --- src/config.rs | 2 +- src/forms.rs | 28 +++++++++++++++------------- src/routes.rs | 4 ++-- templates/contact_form.askama.html | 10 +++++----- 4 files changed, 23 insertions(+), 21 deletions(-) diff --git a/src/config.rs b/src/config.rs index 2a980ac..b56957f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -33,7 +33,7 @@ pub enum CustomFieldType { #[derive(Deserialize)] pub struct CustomField { - pub id: String, + pub key: String, pub label: String, #[serde(default)] pub required_feedback: Option, diff --git a/src/forms.rs b/src/forms.rs index e58cb85..4360ac9 100644 --- a/src/forms.rs +++ b/src/forms.rs @@ -34,6 +34,7 @@ pub struct ContactForm { } impl ContactForm { + /// Build the form from the form map. pub fn from_map( mut map: HashMap, custom_fields: &Vec, @@ -43,21 +44,22 @@ impl ContactForm { .context("id missing in the submitted form!")? .parse() .context("Failed to parse the submitted id!")?; - let captcha_answer = map - .remove("captcha_answer") - .context("captcha_answer missing in the submitted form!")?; - let name = map - .remove("name") - .context("name missing in the submitted form!")?; - let email = map - .remove("email") - .context("email missing in the submitted form!")?; + + // Remove an item with the given key from the map. + let mut remove = |key| { + map.remove(key) + .with_context(|| format!("{} missing in the submitted form!", key)) + }; + + // Default fields. + let captcha_answer = remove("captcha_answer")?; + let name = remove("name")?; + let email = remove("email")?; + + // Custom fields. let mut custom = Vec::with_capacity(custom_fields.len()); for field in custom_fields.iter() { - custom.push( - map.remove(&field.id) - .with_context(|| format!("{} missing in the submitted form!", &field.id))?, - ); + custom.push(remove(&field.key)?); } Ok(Self { diff --git a/src/routes.rs b/src/routes.rs index 9de4ae8..4242f64 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -78,9 +78,9 @@ pub async fn submit( State(config): State>, State(captcha_solutions): State>>, State(mailer): State>, - Form(form): Form>, + Form(map): Form>, ) -> Result { - let form = ContactForm::from_map(form, &config.custom_fields)?; + let form = ContactForm::from_map(map, &config.custom_fields)?; let right_captcha_answer = captcha_solutions .lock() diff --git a/templates/contact_form.askama.html b/templates/contact_form.askama.html index 82002a8..b6a4784 100644 --- a/templates/contact_form.askama.html +++ b/templates/contact_form.askama.html @@ -38,22 +38,22 @@ {% let value = persistant_field_contents.custom[loop.index0] %} {% let required = custom_field.required_feedback.is_some() %} - + {% match custom_field.field_type %} {% when config::CustomFieldType::Text %} {% when config::CustomFieldType::Textarea with { rows } %} {% endmatch %}