Skip to main content

docx_templating/
context.rs

1//! Template context and data lookup.
2//!
3//! Provides the [`Context`] type for supplying data to templates, and the
4//! [`IntoContext`] trait that lets `Template::render` accept JSON, a context or
5//! any borrowed serializable value.
6
7#[cfg(test)]
8use crate::syntax::ast::Path;
9use serde::Serialize;
10use serde_json::Value;
11
12/// Template data context wrapping JSON values.
13///
14/// Provides path resolution for template evaluation.
15///
16/// # Examples
17///
18/// ```
19/// use docx_templating::Context;
20/// use serde_json::json;
21///
22/// // From JSON
23/// let ctx = Context::from_json(json!({
24///     "user": {
25///         "name": "Ada Lovelace"
26///     }
27/// }));
28/// ```
29#[derive(Debug, Clone)]
30pub struct Context {
31    root: Value,
32}
33
34impl Context {
35    /// Create context from a JSON value.
36    pub fn from_json(value: Value) -> Self {
37        Self { root: value }
38    }
39
40    /// Create context from any serializable type.
41    ///
42    /// # Errors
43    ///
44    /// Returns error if serialization to JSON fails.
45    ///
46    /// # Examples
47    ///
48    /// ```
49    /// use docx_templating::Context;
50    /// use serde::Serialize;
51    ///
52    /// #[derive(Serialize)]
53    /// struct User {
54    ///     name: String,
55    ///     age: u32,
56    /// }
57    ///
58    /// let user = User { name: "Ada".into(), age: 36 };
59    /// let ctx = Context::from_serialize(&user).unwrap();
60    /// ```
61    pub fn from_serialize<T: Serialize + ?Sized>(value: &T) -> crate::Result<Self> {
62        let json = serde_json::to_value(value).map_err(ContextError::Serialization)?;
63        Ok(Self::from_json(json))
64    }
65
66    /// Resolve a path to a value reference.
67    ///
68    /// Returns `Ok(Some(&value))` if path exists,
69    /// `Ok(None)` if path is valid but doesn't exist,
70    /// `Err(...)` if path traversal encounters type mismatches.
71    ///
72    /// Paths are an internal representation, so this helper is crate visible
73    /// only. Callers outside the crate reach values by rendering a template.
74    #[cfg(test)]
75    pub(crate) fn resolve(&self, path: &Path) -> crate::Result<Option<&Value>> {
76        crate::domain::engine::resolve_path(&self.root, path).map_err(crate::Error::from)
77    }
78
79    /// Get the root value (internal use).
80    pub(crate) fn root(&self) -> &Value {
81        &self.root
82    }
83}
84
85impl From<Value> for Context {
86    fn from(value: Value) -> Self {
87        Self::from_json(value)
88    }
89}
90
91impl Default for Context {
92    /// An empty context, the same as `Context::from_json(json!({}))`.
93    fn default() -> Self {
94        Self::from_json(Value::Object(serde_json::Map::new()))
95    }
96}
97
98impl Serialize for Context {
99    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
100    where
101        S: serde::Serializer,
102    {
103        self.root.serialize(serializer)
104    }
105}
106
107/// Anything that can be turned into a [`Context`].
108///
109/// [`Template::render`](crate::Template::render) takes `impl IntoContext`, so a
110/// caller can pass whichever form they already have:
111///
112/// - a [`Context`], by value or by reference
113/// - a [`serde_json::Value`], such as the result of [`serde_json::json!`]
114/// - a reference to any [`serde::Serialize`] value, such as a borrowed struct
115///
116/// Passing a reference avoids cloning the data and keeps the struct in the
117/// caller's own type.
118///
119/// # Examples
120///
121/// ```
122/// use docx_templating::{Context, IntoContext};
123/// use serde::Serialize;
124///
125/// #[derive(Serialize)]
126/// struct User {
127///     name: String,
128/// }
129///
130/// let user = User { name: "Ada".into() };
131/// let context = user.into_context().unwrap();
132/// assert!(context.into_context().is_ok());
133/// ```
134pub trait IntoContext {
135    /// Convert this value into a context.
136    ///
137    /// # Errors
138    ///
139    /// Returns [`ContextError::Serialization`] if the value cannot be
140    /// represented as JSON, which only happens for borrowed serializable
141    /// values.
142    fn into_context(self) -> crate::Result<Context>;
143}
144
145impl IntoContext for Context {
146    fn into_context(self) -> crate::Result<Context> {
147        Ok(self)
148    }
149}
150
151impl IntoContext for Value {
152    fn into_context(self) -> crate::Result<Context> {
153        Ok(Context::from_json(self))
154    }
155}
156
157impl<T: Serialize + ?Sized> IntoContext for &T {
158    fn into_context(self) -> crate::Result<Context> {
159        Context::from_serialize(self)
160    }
161}
162
163/// Context error type.
164#[derive(Debug, thiserror::Error)]
165#[non_exhaustive]
166pub enum ContextError {
167    /// Serialization to JSON failed.
168    #[error("failed to serialize value to JSON: {0}")]
169    Serialization(#[source] serde_json::Error),
170}
171
172#[cfg(test)]
173mod tests {
174    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
175
176    use super::*;
177    use crate::syntax::ast::PathSegment;
178    use serde::Serialize;
179    use serde_json::json;
180
181    #[test]
182    fn test_from_json() {
183        let ctx = Context::from_json(json!({"name": "Ada"}));
184        assert!(ctx.root().is_object());
185    }
186
187    #[test]
188    fn test_from_value_trait() {
189        let ctx: Context = json!({"name": "Ada"}).into();
190        assert!(ctx.root().is_object());
191    }
192
193    #[test]
194    fn test_from_serialize() {
195        #[derive(Serialize)]
196        struct User {
197            name: String,
198            age: u32,
199        }
200
201        let user = User {
202            name: "Ada".to_string(),
203            age: 36,
204        };
205        let ctx = Context::from_serialize(&user).unwrap();
206
207        let path = Path::field("name");
208        let value = ctx.resolve(&path).unwrap();
209        assert_eq!(value, Some(&json!("Ada")));
210    }
211
212    #[test]
213    fn test_resolve_top_level() {
214        let ctx = Context::from_json(json!({"name": "Ada"}));
215        let path = Path::field("name");
216
217        let value = ctx.resolve(&path).unwrap();
218        assert_eq!(value, Some(&json!("Ada")));
219    }
220
221    #[test]
222    fn test_resolve_nested() {
223        let ctx = Context::from_json(json!({
224            "user": {
225                "name": "Ada",
226                "age": 36
227            }
228        }));
229
230        let path = Path::new(vec![
231            PathSegment::Field("user".to_string()),
232            PathSegment::Field("name".to_string()),
233        ]);
234
235        let value = ctx.resolve(&path).unwrap();
236        assert_eq!(value, Some(&json!("Ada")));
237    }
238
239    #[test]
240    fn test_resolve_missing_returns_none() {
241        let ctx = Context::from_json(json!({"name": "Ada"}));
242        let path = Path::field("missing");
243
244        let value = ctx.resolve(&path).unwrap();
245        assert_eq!(value, None);
246    }
247
248    #[test]
249    fn test_resolve_type_mismatch_errors() {
250        let ctx = Context::from_json(json!({"items": [1, 2, 3]}));
251        let path = Path::new(vec![
252            PathSegment::Field("items".to_string()),
253            PathSegment::Field("name".to_string()),
254        ]);
255
256        let result = ctx.resolve(&path);
257        assert!(result.is_err());
258    }
259
260    #[test]
261    fn test_default_context_is_an_empty_object() {
262        let ctx = Context::default();
263        assert_eq!(ctx.root(), &json!({}));
264    }
265
266    #[test]
267    fn test_context_serializes_as_its_root_value() {
268        let ctx = Context::from_json(json!({"name": "Ada"}));
269        assert_eq!(serde_json::to_value(&ctx).unwrap(), json!({"name": "Ada"}));
270    }
271
272    #[test]
273    fn test_into_context_accepts_a_context() {
274        let ctx = Context::from_json(json!({"name": "Ada"}));
275        assert_eq!(ctx.into_context().unwrap().root(), &json!({"name": "Ada"}));
276    }
277
278    #[test]
279    fn test_into_context_accepts_a_value() {
280        let ctx = json!({"name": "Ada"}).into_context().unwrap();
281        assert_eq!(ctx.root(), &json!({"name": "Ada"}));
282    }
283
284    #[test]
285    fn test_into_context_accepts_a_borrowed_struct() {
286        #[derive(Serialize)]
287        struct User {
288            name: String,
289        }
290
291        let user = User {
292            name: "Ada".to_owned(),
293        };
294
295        // A plain value reaches the reference impl through method autoref.
296        let ctx = user.into_context().unwrap();
297        assert_eq!(ctx.root(), &json!({"name": "Ada"}));
298    }
299
300    #[test]
301    fn test_into_context_accepts_a_borrowed_context() {
302        let ctx = Context::from_json(json!({"name": "Ada"}));
303        let copied = (&ctx).into_context().unwrap();
304        assert_eq!(copied.root(), &json!({"name": "Ada"}));
305    }
306}