#[cfg(test)]
use crate::syntax::ast::Path;
use serde::Serialize;
use serde_json::Value;
#[derive(Debug, Clone)]
pub struct Context {
root: Value,
}
impl Context {
pub fn from_json(value: Value) -> Self {
Self { root: value }
}
pub fn from_serialize<T: Serialize + ?Sized>(value: &T) -> crate::Result<Self> {
let json = serde_json::to_value(value).map_err(ContextError::Serialization)?;
Ok(Self::from_json(json))
}
#[cfg(test)]
pub(crate) fn resolve(&self, path: &Path) -> crate::Result<Option<&Value>> {
crate::domain::engine::resolve_path(&self.root, path).map_err(crate::Error::from)
}
pub(crate) fn root(&self) -> &Value {
&self.root
}
}
impl From<Value> for Context {
fn from(value: Value) -> Self {
Self::from_json(value)
}
}
impl Default for Context {
fn default() -> Self {
Self::from_json(Value::Object(serde_json::Map::new()))
}
}
impl Serialize for Context {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.root.serialize(serializer)
}
}
pub trait IntoContext {
fn into_context(self) -> crate::Result<Context>;
}
impl IntoContext for Context {
fn into_context(self) -> crate::Result<Context> {
Ok(self)
}
}
impl IntoContext for Value {
fn into_context(self) -> crate::Result<Context> {
Ok(Context::from_json(self))
}
}
impl<T: Serialize + ?Sized> IntoContext for &T {
fn into_context(self) -> crate::Result<Context> {
Context::from_serialize(self)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ContextError {
#[error("failed to serialize value to JSON: {0}")]
Serialization(#[source] serde_json::Error),
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
use super::*;
use crate::syntax::ast::PathSegment;
use serde::Serialize;
use serde_json::json;
#[test]
fn test_from_json() {
let ctx = Context::from_json(json!({"name": "Ada"}));
assert!(ctx.root().is_object());
}
#[test]
fn test_from_value_trait() {
let ctx: Context = json!({"name": "Ada"}).into();
assert!(ctx.root().is_object());
}
#[test]
fn test_from_serialize() {
#[derive(Serialize)]
struct User {
name: String,
age: u32,
}
let user = User {
name: "Ada".to_string(),
age: 36,
};
let ctx = Context::from_serialize(&user).unwrap();
let path = Path::field("name");
let value = ctx.resolve(&path).unwrap();
assert_eq!(value, Some(&json!("Ada")));
}
#[test]
fn test_resolve_top_level() {
let ctx = Context::from_json(json!({"name": "Ada"}));
let path = Path::field("name");
let value = ctx.resolve(&path).unwrap();
assert_eq!(value, Some(&json!("Ada")));
}
#[test]
fn test_resolve_nested() {
let ctx = Context::from_json(json!({
"user": {
"name": "Ada",
"age": 36
}
}));
let path = Path::new(vec![
PathSegment::Field("user".to_string()),
PathSegment::Field("name".to_string()),
]);
let value = ctx.resolve(&path).unwrap();
assert_eq!(value, Some(&json!("Ada")));
}
#[test]
fn test_resolve_missing_returns_none() {
let ctx = Context::from_json(json!({"name": "Ada"}));
let path = Path::field("missing");
let value = ctx.resolve(&path).unwrap();
assert_eq!(value, None);
}
#[test]
fn test_resolve_type_mismatch_errors() {
let ctx = Context::from_json(json!({"items": [1, 2, 3]}));
let path = Path::new(vec![
PathSegment::Field("items".to_string()),
PathSegment::Field("name".to_string()),
]);
let result = ctx.resolve(&path);
assert!(result.is_err());
}
#[test]
fn test_default_context_is_an_empty_object() {
let ctx = Context::default();
assert_eq!(ctx.root(), &json!({}));
}
#[test]
fn test_context_serializes_as_its_root_value() {
let ctx = Context::from_json(json!({"name": "Ada"}));
assert_eq!(serde_json::to_value(&ctx).unwrap(), json!({"name": "Ada"}));
}
#[test]
fn test_into_context_accepts_a_context() {
let ctx = Context::from_json(json!({"name": "Ada"}));
assert_eq!(ctx.into_context().unwrap().root(), &json!({"name": "Ada"}));
}
#[test]
fn test_into_context_accepts_a_value() {
let ctx = json!({"name": "Ada"}).into_context().unwrap();
assert_eq!(ctx.root(), &json!({"name": "Ada"}));
}
#[test]
fn test_into_context_accepts_a_borrowed_struct() {
#[derive(Serialize)]
struct User {
name: String,
}
let user = User {
name: "Ada".to_owned(),
};
let ctx = user.into_context().unwrap();
assert_eq!(ctx.root(), &json!({"name": "Ada"}));
}
#[test]
fn test_into_context_accepts_a_borrowed_context() {
let ctx = Context::from_json(json!({"name": "Ada"}));
let copied = (&ctx).into_context().unwrap();
assert_eq!(copied.root(), &json!({"name": "Ada"}));
}
}