json_template/context/
mod.rs1use std::path::PathBuf;
4
5use serde_json::Value;
6
7use crate::{Deserializer, Functions, GetDot, Placeholder, JSON};
8
9#[derive(Default, Clone)]
11pub struct Context {
12 data: Value,
14 directory: Option<PathBuf>,
16 functions: Functions,
18 current: Value
20}
21
22impl Context {
23 pub fn new() -> Self {
25 Self::default()
26 }
27
28 pub fn with_data(mut self, data: Value) -> Self {
30 self.data = data.into();
31 self
32 }
33
34 pub fn set_data(&mut self, data: Value) -> &mut Self {
36 self.data = data.into();
37 self
38 }
39
40 pub fn data(&self) -> &Value {
42 &self.data
43 }
44
45 pub fn set_function(&mut self, name: impl AsRef<str>, function: impl Fn(&Deserializer, &Context, &Placeholder) -> serde_json::Result<Value> + 'static) -> &mut Self {
47 self.functions.register(name, function);
48 self
49 }
50
51 pub fn with_function(mut self, name: impl AsRef<str>, function: impl Fn(&Deserializer, &Context, &Placeholder) -> serde_json::Result<Value> + 'static) -> Self {
53 self.set_function(name, function);
54 self
55 }
56
57 pub fn functions(&self) -> &Functions {
59 &self.functions
60 }
61
62 pub fn with_override(mut self, new_value: Value) -> Self {
64 self.override_data(new_value);
65 self
66 }
67
68 pub fn override_data(&mut self, new_value: Value) -> &mut Self {
70 self.data.override_recursive(new_value);
71 self
72 }
73
74 pub fn with_additional_data(mut self, new_value: Value) -> Self {
76 self.add_data(new_value);
77 self
78 }
79
80 pub fn add_data(&mut self, new_value: Value) -> &mut Self {
82 self.data.add_recursive(new_value);
83 self
84 }
85
86 pub fn with_directory(mut self, directory: Option<PathBuf>) -> Self {
88 self.directory = directory;
89 self
90 }
91
92 pub fn set_directory(&mut self, directory: Option<PathBuf>) -> &mut Self {
94 self.directory = directory;
95 self
96 }
97
98 pub fn directory(&self) -> Option<&PathBuf> {
100 self.directory.as_ref()
101 }
102
103 pub(crate) fn set_current_data(&mut self, current: Value) {
104 self.current = current;
105 }
106
107 pub fn find(&self, deserializer: &Deserializer, placeholder: &Placeholder) -> serde_json::Result<Value> {
109 self
110 .data
111 .get_dot_deserializing(placeholder.path(), deserializer, self)
112 .or_else(|_| self.current.get_dot_deserializing(placeholder.path(), deserializer, self))
113 }
114}