use crate::{
error::Result,
library::{fault, string},
value::{Arg, Object, Value, ValueMap},
};
#[derive(Debug)]
struct Errors<'a> {
bags: ValueMap<'a>,
current: String,
}
pub(crate) fn error_bag<'a>(bags: ValueMap<'a>, name: &str) -> Value<'a> {
Value::object(Errors {
bags,
current: name.to_owned(),
})
}
pub(super) fn messages<'a>(bags: &ValueMap<'a>, bag: &str, field: &str) -> Result<Vec<Value<'a>>> {
let Some(value) = bags.get(bag).and_then(|bag| bag.field(field)) else {
return Ok(Vec::new());
};
Ok(value
.entries(100_000)?
.into_iter()
.map(|(_, item)| item)
.collect())
}
impl<'a> Object<'a> for Errors<'a> {
fn type_name(&self) -> &'static str {
"errors"
}
fn method(&self, name: &str, args: Vec<Arg<'a, '_>>) -> Option<Result<Value<'a>>> {
Some((|| {
Ok(match (name, args.as_slice()) {
("bag", [Arg::Value(bag)]) => error_bag(self.bags.clone(), string(bag)?),
("has" | "first" | "get", [Arg::Value(field)]) => {
let messages = messages(&self.bags, &self.current, string(field)?)?;
match name {
"has" => Value::Bool(!messages.is_empty()),
"first" => messages
.into_iter()
.next()
.unwrap_or_else(|| Value::string("")),
_ => Value::List(messages),
}
}
("all" | "any", []) => {
let mut messages = Vec::new();
if let Some(bag) = self.bags.get(&self.current) {
for (_, field) in bag.entries(100_000)? {
for (_, message) in field.entries(100_000)? {
messages.push(message);
}
}
}
if name == "any" {
Value::Bool(!messages.is_empty())
} else {
Value::List(messages)
}
}
_ => return Err(fault(format!("invalid errors method: {name}"))),
})
})())
}
}