27 lines
1.1 KiB
Rust
27 lines
1.1 KiB
Rust
//! Object member lookup with error paths. Typed readers are re-exported for one import site.
|
|
|
|
pub use super::path::{at, join};
|
|
pub use super::scalar::{flag, items, number, text, whole_u64, whole_u8};
|
|
use super::Value;
|
|
use crate::fault::Fault;
|
|
|
|
fn lookup<'a>(object: &'a Value, path: &str, key: &str) -> Result<Option<&'a Value>, Fault> {
|
|
match object {
|
|
Value::Object(members) => Ok(members.iter().find(|(k, _)| k == key).map(|(_, v)| v)),
|
|
other => Err(Fault::Invalid {
|
|
field: if path.is_empty() { "request".to_string() } else { path.to_string() },
|
|
detail: format!("expected an object, found {}", other.kind()),
|
|
}),
|
|
}
|
|
}
|
|
|
|
/// The member must exist (it may still be `null`; typed readers then reject it).
|
|
pub fn required<'a>(object: &'a Value, path: &str, key: &str) -> Result<&'a Value, Fault> {
|
|
lookup(object, path, key)?.ok_or_else(|| Fault::Missing(join(path, key)))
|
|
}
|
|
|
|
/// Absent and `null` both mean "not given".
|
|
pub fn optional<'a>(object: &'a Value, path: &str, key: &str) -> Result<Option<&'a Value>, Fault> {
|
|
Ok(lookup(object, path, key)?.filter(|v| **v != Value::Null))
|
|
}
|