use serde_json::Value;
use crate::syntax::ast::{Path, PathSegment};
use super::conversion::type_name;
use super::error::RenderError;
pub(crate) fn resolve_path<'a>(
root: &'a Value,
path: &Path,
) -> Result<Option<&'a Value>, RenderError> {
let mut current = root;
for segment in &path.segments {
match segment {
PathSegment::Current => return Err(RenderError::CurrentItemOutsideLoop),
PathSegment::Field(name) => match current {
Value::Object(map) => match map.get(name) {
Some(value) => current = value,
None => return Ok(None),
},
other => {
return Err(RenderError::TypeMismatch {
expected: "object",
actual: type_name(other),
path: format_path(path),
part: None,
});
}
},
PathSegment::Index(index) => match current {
Value::Array(items) => match items.get(*index) {
Some(value) => current = value,
None => return Ok(None),
},
other => {
return Err(RenderError::TypeMismatch {
expected: "array",
actual: type_name(other),
path: format_path(path),
part: None,
});
}
},
}
}
Ok(Some(current))
}
pub(crate) fn format_path(path: &Path) -> String {
if path.segments.is_empty() {
return ".".to_owned();
}
path.segments
.iter()
.map(|segment| match segment {
PathSegment::Field(name) => name.clone(),
PathSegment::Index(index) => index.to_string(),
PathSegment::Current => ".".to_owned(),
})
.collect::<Vec<_>>()
.join(".")
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use super::*;
use serde_json::json;
#[test]
fn resolves_fields_and_indices() {
let root = json!({"user": {"names": ["Ada", "Grace"]}});
let path = Path::new(vec![
PathSegment::Field("user".to_owned()),
PathSegment::Field("names".to_owned()),
PathSegment::Index(1),
]);
assert_eq!(resolve_path(&root, &path).unwrap(), Some(&json!("Grace")));
}
#[test]
fn missing_field_is_none() {
let root = json!({"user": {}});
let path = Path::field("user.name");
assert_eq!(resolve_path(&root, &path).unwrap(), None);
}
#[test]
fn type_mismatch_is_an_error() {
let root = json!({"items": []});
let path = Path::new(vec![
PathSegment::Field("items".to_owned()),
PathSegment::Field("name".to_owned()),
]);
assert!(matches!(
resolve_path(&root, &path),
Err(RenderError::TypeMismatch { .. })
));
}
}