Skip to main content

nitr_std/validate/engine/
errors.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! The verdict a failed validation carries: one entry per failing path
7//! with its rule code, parameters and message, in the three shapes the
8//! callers need — a Lua table, a JSON body, and the Rust struct.
9
10use mlua::{Lua, Table, Value};
11
12use super::super::message::Param;
13
14/// One failed rule.
15#[derive(Debug, Clone, PartialEq)]
16pub struct ErrorEntry {
17    /// The failing path (`text`, `tags[2]`, `home.city`; `$` for the root).
18    pub path: String,
19    /// The nearest named field (`tags` for `tags[2]`), empty for the root.
20    pub field: String,
21    /// The request part the path was prefixed with (`body`, `query`, …);
22    /// none for a schema checked on its own.
23    pub part: Option<String>,
24    /// The rule code (`required`, `min_len`, `check`, …).
25    pub rule: String,
26    /// The rendered, sanitized message.
27    pub message: String,
28    /// The rule's own parameters, never the input.
29    pub(crate) params: Vec<(String, Param)>,
30    /// The field's `label`, when it has one.
31    pub label: Option<String>,
32}
33
34impl ErrorEntry {
35    /// The parameters as JSON, for the 422 body.
36    pub fn params_json(&self) -> Option<serde_json::Value> {
37        if self.params.is_empty() {
38            return None;
39        }
40        Some(serde_json::Value::Object(
41            self.params
42                .iter()
43                .map(|(k, v)| (k.clone(), v.to_json()))
44                .collect(),
45        ))
46    }
47}
48
49/// The verdict when validation fails: the summary, and every failing
50/// path with its message and rule.
51#[derive(Debug, Clone, PartialEq)]
52pub struct ValidationError {
53    /// The summary line (`validation failed` unless overridden).
54    pub message: String,
55    /// Sorted by path; one entry per failing path.
56    pub entries: Vec<ErrorEntry>,
57}
58
59impl ValidationError {
60    /// A single failure not tied to a schema field: a body that is not
61    /// JSON, say. `rule` is the code, `message` the text.
62    pub fn single(rule: &str, message: &str) -> Self {
63        Self {
64            message: "validation failed".into(),
65            entries: vec![ErrorEntry {
66                path: "$".into(),
67                field: String::new(),
68                part: None,
69                rule: rule.into(),
70                message: message.into(),
71                params: Vec::new(),
72                label: None,
73            }],
74        }
75    }
76
77    /// Prefixes every path with a request part (`body`, `query`, …): the
78    /// root `$` becomes the bare part name.
79    pub fn prefix(&mut self, part: &str) {
80        for entry in &mut self.entries {
81            entry.path = if entry.path == "$" {
82                part.to_string()
83            } else {
84                format!("{part}.{}", entry.path)
85            };
86            entry.part = Some(part.to_string());
87        }
88    }
89
90    /// Appends another part's failures, keeping the list sorted.
91    pub fn merge(&mut self, other: Self) {
92        self.entries.extend(other.entries);
93        self.entries.sort_by(|a, b| a.path.cmp(&b.path));
94    }
95
96    /// `{ message, fields = { path = message }, errors = { {...} } }`.
97    pub fn to_lua(&self, lua: &Lua) -> mlua::Result<Table> {
98        let err = lua.create_table()?;
99        err.set("code", "VALIDATION_FAILED")?;
100        err.set("message", self.message.as_str())?;
101        let fields = lua.create_table()?;
102        let errors = lua.create_table_with_capacity(self.entries.len(), 0)?;
103        for (i, entry) in self.entries.iter().enumerate() {
104            if fields.get::<Value>(entry.path.as_str())?.is_nil() {
105                fields.set(entry.path.as_str(), entry.message.as_str())?;
106            }
107            let e = lua.create_table()?;
108            e.set("path", entry.path.as_str())?;
109            if let Some(part) = &entry.part {
110                e.set("part", part.as_str())?;
111            }
112            e.set("field", entry.field.as_str())?;
113            e.set("rule", entry.rule.as_str())?;
114            e.set("message", entry.message.as_str())?;
115            if !entry.params.is_empty() {
116                let params = lua.create_table()?;
117                for (k, v) in &entry.params {
118                    params.set(k.as_str(), v.to_lua(lua)?)?;
119                }
120                e.set("params", params)?;
121            }
122            if let Some(label) = &entry.label {
123                e.set("label", label.as_str())?;
124            }
125            errors.raw_set(i + 1, e)?;
126        }
127        err.set("fields", fields)?;
128        err.set("errors", errors)?;
129        Ok(err)
130    }
131
132    /// The same shape as JSON, with `code = "VALIDATION_FAILED"`.
133    pub fn to_json(&self) -> serde_json::Value {
134        let mut fields = serde_json::Map::new();
135        let mut errors = Vec::with_capacity(self.entries.len());
136        for entry in &self.entries {
137            fields
138                .entry(entry.path.clone())
139                .or_insert_with(|| serde_json::Value::String(entry.message.clone()));
140            let mut e = serde_json::Map::new();
141            e.insert("path".into(), entry.path.clone().into());
142            if let Some(part) = &entry.part {
143                e.insert("part".into(), part.clone().into());
144            }
145            e.insert("field".into(), entry.field.clone().into());
146            e.insert("rule".into(), entry.rule.clone().into());
147            e.insert("message".into(), entry.message.clone().into());
148            if let Some(params) = entry.params_json() {
149                e.insert("params".into(), params);
150            }
151            if let Some(label) = &entry.label {
152                e.insert("label".into(), label.clone().into());
153            }
154            errors.push(serde_json::Value::Object(e));
155        }
156        serde_json::json!({
157            "code": "VALIDATION_FAILED",
158            "message": self.message,
159            "fields": serde_json::Value::Object(fields),
160            "errors": errors,
161        })
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    fn entry(path: &str, field: &str, rule: &str) -> ErrorEntry {
170        ErrorEntry {
171            path: path.into(),
172            field: field.into(),
173            part: None,
174            rule: rule.into(),
175            message: format!("{rule} failed"),
176            params: vec![("min".into(), Param::Num(3.0))],
177            label: None,
178        }
179    }
180
181    /// The part is what `prefix` said, never a guess from the path text:
182    /// a field named `body` is a field named `body`.
183    #[test]
184    fn prefixing_turns_the_root_into_the_part_name() {
185        let mut err = ValidationError::single("json", "must be valid JSON");
186        err.prefix("body");
187        assert_eq!(err.entries[0].path, "body");
188        let json = err.to_json();
189        assert_eq!(json["errors"][0]["part"], "body");
190        assert_eq!(json["errors"][0]["field"], "");
191
192        let mut err = ValidationError {
193            message: "validation failed".into(),
194            entries: vec![entry("body", "body", "required")],
195        };
196        let json = err.to_json();
197        assert!(json["errors"][0].get("part").is_none(), "{json}");
198        assert_eq!(json["errors"][0]["field"], "body");
199        err.prefix("query");
200        let json = err.to_json();
201        assert_eq!(json["errors"][0]["path"], "query.body");
202        assert_eq!(json["errors"][0]["part"], "query");
203        assert_eq!(json["errors"][0]["field"], "body");
204    }
205
206    #[test]
207    fn merge_keeps_paths_sorted_and_json_carries_every_field() {
208        let mut err = ValidationError {
209            message: "validation failed".into(),
210            entries: vec![entry("b", "b", "min")],
211        };
212        err.prefix("query");
213        let mut body = ValidationError {
214            message: String::new(),
215            entries: vec![entry("a", "a", "required")],
216        };
217        body.prefix("body");
218        err.merge(body);
219        assert_eq!(err.entries[0].path, "body.a");
220        let json = err.to_json();
221        assert_eq!(json["code"], "VALIDATION_FAILED");
222        assert_eq!(json["fields"]["query.b"], "min failed");
223        assert_eq!(json["errors"][1]["part"], "query");
224        assert_eq!(json["errors"][1]["params"]["min"], 3.0);
225    }
226}