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