Skip to main content

tablo_core/resource/
write_error.rs

1//! [`WriteError`]: why a record fn or an action's run wrote nothing.
2
3use derive_where::derive_where;
4
5use crate::form::{FieldErrors, FormFields};
6
7/// Why a record fn or an action's run wrote nothing: a refusal the page shows, or a failure.
8///
9/// Either way the handler rolls the transaction back, so whatever the fn wrote before it returned
10/// is undone.
11///
12/// - [`Refused`](Self::Refused) renders the form again with status 200, each error under the
13///   control of the field it names, as a [`validate_record`](crate::Resource::validate_record)
14///   error does. A record fn keys its errors by its record form, an action's run by its input, and
15///   picks a field by its name, so a renamed field fails to compile rather than render no message.
16/// - [`Declined`](Self::Declined) refuses with a message that belongs to no field: a paid invoice
17///   that cannot be deleted. A record form renders again with the message above its fields; a
18///   delete, a restore or an action flashes it and lands back where it started.
19/// - [`Failed`](Self::Failed) answers as a failed write does: a record fn's collision on a unique
20///   index renders under the field's control, a save another save overtook renders the stale form,
21///   and any other error flashes the failure toast and answers with the error.
22///
23/// A refusal is the answer to a rule that reads the database: a stock level, a quota, a
24/// uniqueness no index models. A rule the write itself enforces holds against concurrent writes:
25/// an update filtered on the stock it needs that matches no row refuses the very write it would
26/// have made.
27///
28/// `?` turns any error a [`topcoat::Error`] takes into [`Failed`](Self::Failed), and a
29/// [`FieldErrors`] into [`Refused`](Self::Refused):
30///
31/// ```rust
32/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
33/// # struct Order { #[key] #[auto] id: uuid::Uuid, sku: String, quantity: i64 }
34/// # #[derive(Debug, toasty::Model)]
35/// # struct Stock { #[key] sku: String, level: i64 }
36/// # #[derive(Debug, Clone, tablo_core::RecordForm)]
37/// # #[form(model = Order)]
38/// # struct OrderForm { sku: String, quantity: i64 }
39/// # struct OrderResource;
40/// use tablo_core::{RecordForm, Resource, WriteError, write_create};
41/// use topcoat::context::Cx;
42///
43/// impl Resource for OrderResource {
44///     type Model = Order;
45///     type Form = OrderForm;
46///
47///     async fn create_record(
48///         cx: &Cx,
49///         form: OrderForm,
50///         ex: &mut dyn toasty::Executor,
51///     ) -> Result<Order, WriteError<OrderForm>> {
52///         let stock = Stock::filter_by_sku(&form.sku)
53///             .first()
54///             .exec(&mut *ex)
55///             .await?;
56///         if stock.is_none_or(|stock| stock.level < form.quantity) {
57///             return Err(WriteError::<OrderForm>::field(
58///                 |f| f.quantity,
59///                 "Not enough in stock",
60///             ));
61///         }
62///         write_create::<Self>(cx, form, ex).await
63///     }
64/// }
65/// ```
66#[derive_where(Debug; F::Field)]
67#[non_exhaustive]
68pub enum WriteError<F: FormFields = String> {
69    /// The submission cannot stand: render the form again with these errors.
70    Refused(FieldErrors<F>),
71    /// The write cannot stand, for a reason that names no field: show this message.
72    Declined(crate::Text),
73    /// The write failed: answer with this error and the failure toast.
74    Failed(topcoat::Error),
75}
76
77impl<F: FormFields> WriteError<F> {
78    /// Refuse the submission with `message` under `field`: `WriteError::field(|f| f.room, ..)`.
79    pub fn field(pick: impl FnOnce(F::Keys) -> F::Field, message: impl Into<crate::Text>) -> Self {
80        let mut errors = FieldErrors::new();
81        errors.add(pick, message);
82        Self::Refused(errors)
83    }
84
85    /// Decline the write with `message`, which names no field.
86    pub fn declined(message: impl Into<crate::Text>) -> Self {
87        Self::Declined(message.into())
88    }
89
90    /// This error, its refusal keyed by the form key `key` gives each field.
91    pub(crate) fn keyed(self, key: fn(F::Field) -> &'static str) -> WriteError {
92        match self {
93            Self::Refused(errors) => WriteError::Refused(errors.keyed(key)),
94            Self::Declined(message) => WriteError::Declined(message),
95            Self::Failed(error) => WriteError::Failed(error),
96        }
97    }
98}
99
100impl<F: FormFields> From<FieldErrors<F>> for WriteError<F> {
101    fn from(errors: FieldErrors<F>) -> Self {
102        Self::Refused(errors)
103    }
104}
105
106impl<F: FormFields, E: Into<topcoat::Error>> From<E> for WriteError<F> {
107    fn from(error: E) -> Self {
108        Self::Failed(error.into())
109    }
110}