Skip to content

Commit

Permalink
Merge pull request #6 from reciperium/fix/serde
Browse files Browse the repository at this point in the history
feat: add tag to token and add support for json-schema
  • Loading branch information
woile authored Apr 24, 2024
2 parents 4f21c71 + 0792de4 commit 974ea84
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions crates/recipe-parser/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ homepage = { workspace = true }
categories = ["command-line-interface", "parser-implementations"]

[dependencies]
schemars = { version = "0.8.16", optional = true }
serde = { version = "1", features = ["derive"], optional = true }
winnow = "0.6.6"

Expand All @@ -23,4 +24,9 @@ serde_json = "1.0"
path = "src/lib.rs"

[features]

# Adds serde Serialize implementation to Token
serde = ["dep:serde"]

# Add JsonSchema generation for Token
schemars = ["dep:schemars"]
40 changes: 40 additions & 0 deletions crates/recipe-parser/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ fn parse_backstory<'a>(input: &mut Input<'a>) -> PResult<&'a str> {

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
// if you use `zod` for example, using a tag makes it easy to use an undiscriminated union
#[cfg_attr(feature = "serde", serde(tag = "token"))]
pub enum Token<'a> {
Metadata {
key: &'a str,
Expand Down Expand Up @@ -553,4 +556,41 @@ mod test {
assert_eq!(expected, fmt_recipe);
println!("{:?}", recipe);
}

#[test]
#[cfg(feature = "serde")]
fn test_token_serialization_works() {
let token = Token::Ingredient {
name: "quinoa",
quantity: Some("200"),
unit: Some("gr"),
};

let serialized = serde_json::to_string(&token).expect("failed to serialize");
println!("{}", serialized);
}

#[test]
#[cfg(feature = "serde")]
fn test_token_serialization_creates_right_payload() {
let token = Token::Ingredient {
name: "quinoa",
quantity: Some("200"),
unit: Some("gr"),
};

let serialized = serde_json::to_string(&token).expect("failed to serialize");
assert_eq!(
serialized,
r#"{"token":"Ingredient","name":"quinoa","quantity":"200","unit":"gr"}"#
);
}

#[test]
#[cfg(feature = "schemars")]
fn test_token_json_schema_generation() {
use schemars::schema_for;
let schema = schema_for!(Token);
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
}

0 comments on commit 974ea84

Please sign in to comment.