Skip to content

Commit

Permalink
Implement Deserialize for Template
Browse files Browse the repository at this point in the history
booleans, numeric and nulls are now supported for query values

Closes LucasPickering#141
  • Loading branch information
maksimowiczm committed Apr 22, 2024
1 parent 07069bc commit fd9c3d2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
32 changes: 29 additions & 3 deletions src/collection/cereal.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
//! Serialization/deserialization helpers for various types

use crate::collection::{
recipe_tree::RecipeNode, Chain, ChainId, Profile, ProfileId, RecipeId,
use crate::{
collection::{
recipe_tree::RecipeNode, Chain, ChainId, Profile, ProfileId, RecipeId,
},
template::Template,
};
use serde::{Deserialize, Deserializer};
use serde::{de::Error, Deserialize, Deserializer};
use serde_yaml::Value;
use std::hash::Hash;

/// A type that has an `id` field. This is ripe for a derive macro, maybe a fun
Expand Down Expand Up @@ -62,6 +66,28 @@ where
Ok(map)
}

impl<'de> Deserialize<'de> for Template {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value: Value = Deserialize::deserialize(deserializer)?;

let str_value =
match value {
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.to_string(),
Value::String(s) => s,
Value::Null => "null".to_string(),
_ => return Err(Error::custom(
"Invalid type, must be a string, number, boolean, or null",
)),
};

Template::try_from(str_value).map_err(|e| Error::custom(e.to_string()))
}
}

/// Serialize/deserialize a duration with unit shorthand. This does *not* handle
/// subsecond precision. Supported units are:
/// - s
Expand Down
4 changes: 2 additions & 2 deletions src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::{
};
use derive_more::{Deref, Display};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde::Serialize;
use std::{fmt::Debug, sync::atomic::AtomicU8};

/// Maximum number of layers of nested templates
Expand Down Expand Up @@ -60,7 +60,7 @@ pub struct TemplateContext {

/// A immutable string that can contain templated content. The string is parsed
/// during creation to identify template keys, hence the immutability.
#[derive(Clone, Debug, Deref, Display, Serialize, Deserialize)]
#[derive(Clone, Debug, Deref, Display, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
#[display("{template}")]
#[serde(try_from = "String", into = "String")]
Expand Down

0 comments on commit fd9c3d2

Please sign in to comment.