1
//! The `template-create` form submit: an optional name and the source.
2

            
3
use forms::{FormValues, TEMPLATE_CREATE};
4
use server::command::CmdResult;
5
use server::command::template::CreateTemplate;
6
use uuid::Uuid;
7

            
8
use super::Failure;
9
use super::transaction_rows::error_at;
10
use crate::template::validate_source;
11

            
12
const CTX: &str = "template-create";
13

            
14
/// The source, else a field error at `source` when it does not compile.
15
3057
pub(super) fn checked_source(values: &FormValues) -> Result<String, Failure> {
16
3057
    let source = values.text("source").unwrap_or_default();
17
3057
    validate_source(source).map_err(|message| error_at("source".to_string(), message))?;
18
2575
    Ok(source.to_string())
19
3057
}
20

            
21
/// `template-create` submit: the id of the new template.
22
2090
pub(super) async fn create_template(user_id: Uuid, values: &FormValues) -> Result<Uuid, Failure> {
23
2090
    let errors = values.check(&TEMPLATE_CREATE);
24
2090
    if !errors.is_empty() {
25
1
        return Err(errors.into());
26
2089
    }
27
2089
    let mut command = CreateTemplate::new()
28
2089
        .user_id(user_id)
29
2089
        .source(checked_source(values)?);
30
1768
    if let Some(name) = values.text("name") {
31
1285
        command = command.name(name.to_string());
32
483
    }
33
1768
    match command
34
1768
        .run()
35
1768
        .await
36
        .map_err(|err| Failure::from_command(CTX, err))?
37
    {
38
1768
        Some(CmdResult::Uuid(id)) => Ok(id),
39
        other => Err(Failure::Internal(wasmtime::Error::msg(format!(
40
            "{CTX}: unexpected create result {other:?}"
41
        )))),
42
    }
43
2090
}