1
//! `template-edit` submit: syntax, compile check, then the one `EditTemplate`
2
//! command under the template's key locks.
3

            
4
use forms::{FormValues, TEMPLATE_EDIT};
5
use server::command::template::EditTemplate;
6
use server::command::{CmdError, CmdResult};
7
use server::template_state::STALE_TEMPLATE;
8
use uuid::Uuid;
9

            
10
use super::Failure;
11
use super::template_create::checked_source;
12
use super::transaction_rows::error_at;
13

            
14
const CTX: &str = "submit-form";
15

            
16
/// Validate `template-edit` values and apply the name and the source.
17
968
pub(super) async fn edit_template(user_id: Uuid, values: &FormValues) -> Result<Uuid, Failure> {
18
968
    let errors = values.check(&TEMPLATE_EDIT);
19
968
    if !errors.is_empty() {
20
        return Err(errors.into());
21
968
    }
22
1775
    let text = |key| values.text(key).unwrap_or_default();
23
968
    let template_id = Uuid::parse_str(text("id").trim())
24
        .map_err(|_| error_at("id".to_string(), "unknown template"))?;
25
968
    let mut command = EditTemplate::new()
26
968
        .user_id(user_id)
27
968
        .template_id(template_id)
28
968
        .source(checked_source(values)?)
29
807
        .revision(text("revision").trim().to_string());
30
807
    if let Some(name) = values.text("name") {
31
807
        command = command.name(name.to_string());
32
    }
33
807
    match command.run().await {
34
644
        Ok(Some(CmdResult::Uuid(id))) => Ok(id),
35
        Ok(other) => Err(Failure::Internal(wasmtime::Error::msg(format!(
36
            "{CTX}: unexpected edit result {other:?}"
37
        )))),
38
163
        Err(err) => Err(edit_failure(err)),
39
    }
40
968
}
41

            
42
/// The stale revision is a field error and an unknown template one at `id`;
43
/// the rest as elsewhere.
44
163
fn edit_failure(err: CmdError) -> Failure {
45
163
    match err {
46
162
        CmdError::Args(message) if message == STALE_TEMPLATE => {
47
162
            error_at("revision".to_string(), message).into()
48
        }
49
1
        err if err.is_missing_row() => error_at("id".to_string(), "unknown template").into(),
50
        other => Failure::from_command(CTX, other),
51
    }
52
163
}