pub type PreProcessFn = Box<dyn Fn(serde_json::Value) -> serde_json::Value + Send + Sync>;
pub type PostProcessFn = Box<dyn Fn(serde_json::Value) -> serde_json::Value + Send + Sync>;
pub type PreSaveFn = Box<dyn Fn(serde_json::Value) -> serde_json::Value + Send + Sync>;
pub type PostSaveFn = Box<dyn Fn(serde_json::Value) -> serde_json::Value + Send + Sync>;
#[derive(Default)]
pub struct LoadContext {
pub pre_process: Option<PreProcessFn>,
pub post_process: Option<PostProcessFn>,
}
impl std::fmt::Debug for LoadContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LoadContext")
.field("pre_process", &self.pre_process.as_ref().map(|_| "..."))
.field("post_process", &self.post_process.as_ref().map(|_| "..."))
.finish()
}
}
impl LoadContext {
pub fn new() -> Self {
Self::default()
}
pub fn process_input(&self, data: serde_json::Value) -> serde_json::Value {
if let Some(ref f) = self.pre_process {
f(data)
} else {
data
}
}
pub fn process_output(&self, result: serde_json::Value) -> serde_json::Value {
if let Some(ref f) = self.post_process {
f(result)
} else {
result
}
}
}
pub struct SaveContext {
pub pre_save: Option<PreSaveFn>,
pub post_save: Option<PostSaveFn>,
pub collection_format: String,
pub use_shorthand: bool,
}
impl std::fmt::Debug for SaveContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SaveContext")
.field("pre_save", &self.pre_save.as_ref().map(|_| "..."))
.field("post_save", &self.post_save.as_ref().map(|_| "..."))
.field("collection_format", &self.collection_format)
.field("use_shorthand", &self.use_shorthand)
.finish()
}
}
impl Default for SaveContext {
fn default() -> Self {
Self {
pre_save: None,
post_save: None,
collection_format: "object".to_string(),
use_shorthand: true,
}
}
}
impl SaveContext {
pub fn new() -> Self {
Self::default()
}
pub fn process_object(&self, obj: serde_json::Value) -> serde_json::Value {
if let Some(ref f) = self.pre_save {
f(obj)
} else {
obj
}
}
pub fn process_dict(&self, data: serde_json::Value) -> serde_json::Value {
if let Some(ref f) = self.post_save {
f(data)
} else {
data
}
}
pub fn to_yaml(&self, data: &serde_json::Value) -> Result<String, serde_yaml::Error> {
serde_yaml::to_string(data)
}
pub fn to_json(
&self,
data: &serde_json::Value,
indent: bool,
) -> Result<String, serde_json::Error> {
if indent {
serde_json::to_string_pretty(data)
} else {
serde_json::to_string(data)
}
}
}