Skip to main content

web/pages/forms/
create.rs

1//! The create pages over a shared mutation form.
2
3use std::collections::BTreeMap;
4
5use axum::response::Response;
6use forms::{FieldError, Form, FormValues};
7use uuid::Uuid;
8
9use super::attempt::{Attempt, attempt};
10use super::references;
11use crate::form_invalid::form_invalid;
12use crate::form_render::{References, render_form};
13use crate::response::WebError;
14
15/// A create form and the path it posts to.
16pub struct Create {
17    pub form: &'static Form,
18    pub action: &'static str,
19}
20
21/// A submit's answer: the stored entity with its notice, or the response
22/// that replaces the form.
23pub enum Created {
24    Saved { id: Uuid, notice: Option<String> },
25    Invalid(Response),
26}
27
28impl Create {
29    fn render(
30        &self,
31        values: &FormValues,
32        errors: &[FieldError],
33        references: &References,
34    ) -> Result<String, WebError> {
35        render_form(self.form, values, errors, self.action, references)
36            .map_err(|e| WebError::internal("Create form render failed", e))
37    }
38
39    /// The empty form.
40    pub async fn blank(&self, user_id: Uuid) -> Result<String, WebError> {
41        let references = references(self.form, user_id, BTreeMap::new()).await?;
42        self.render(&FormValues::default(), &[], &references)
43    }
44
45    pub async fn submit(
46        &self,
47        user_id: Uuid,
48        pairs: Vec<(String, String)>,
49    ) -> Result<Created, WebError> {
50        Ok(match attempt(self.form, user_id, pairs).await? {
51            Attempt::Saved { id, notice } => Created::Saved { id, notice },
52            Attempt::Rejected(rejected) => Created::Invalid(form_invalid(
53                self.form,
54                self.render(&rejected.values, &rejected.errors, &rejected.references)?,
55            )),
56        })
57    }
58}