Lines
80.95 %
Functions
85.71 %
Branches
100 %
//! The `script-create` form submit: an optional name, the source and the state.
use forms::{FormValues, SCRIPT_CREATE};
use server::command::CmdResult;
use server::command::script::CreateScript;
use uuid::Uuid;
use super::Failure;
use super::transaction_rows::error_at;
use crate::script::{ScriptError, compile_script};
const CTX: &str = "script-create";
/// The source with its bytecode, else a field error at `source` when it does
/// not compile.
pub(super) fn compiled(values: &FormValues) -> Result<(String, Vec<u8>), Failure> {
let source = values.text("source").unwrap_or_default();
match compile_script(source) {
Ok(bytecode) => Ok((source.to_string(), bytecode)),
Err(ScriptError::Compile(message)) => Err(error_at("source".to_string(), message).into()),
Err(other) => Err(Failure::Internal(wasmtime::Error::msg(format!(
"{CTX}: {other}"
)))),
}
/// The name, unless it is absent or blank.
pub(super) fn named(values: &FormValues) -> Option<String> {
values
.text("name")
.map(str::trim)
.filter(|name| !name.is_empty())
.map(str::to_string)
/// An absent state keeps the script on.
pub(super) fn enabled(values: &FormValues) -> bool {
values.text("enabled") != Some("false")
/// `script-create` submit: the id of the new script.
pub(super) async fn create_script(user_id: Uuid, values: &FormValues) -> Result<Uuid, Failure> {
let errors = values.check(&SCRIPT_CREATE);
if !errors.is_empty() {
return Err(errors.into());
let (source, bytecode) = compiled(values)?;
let mut command = CreateScript::new()
.user_id(user_id)
.source(source)
.bytecode(bytecode)
.enabled(enabled(values));
if let Some(name) = named(values) {
command = command.name(name);
match command
.run()
.await
.map_err(|err| Failure::from_command(CTX, err))?
{
Some(CmdResult::Uuid(id)) => Ok(id),
other => Err(Failure::Internal(wasmtime::Error::msg(format!(
"{CTX}: unexpected create result {other:?}"