Skip to content

Commit

Permalink
fix: use serde content for token enum
Browse files Browse the repository at this point in the history
BREAKING CHANGE:
json output is no longer like:
```json
{"token": "Ingredient", "name": "foo", "amount": "1", "unit": "gr"}
```
now:
```json
{"token": "Ingredient", "content": {"name": "foo", "amount": "1", "unit": "gr"}}
```
The problem is that serde was failing to serialize enum variants that contained a single string
  • Loading branch information
woile committed Apr 24, 2024
1 parent 4407b36 commit 276a282
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions crates/recipe-parser/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ fn parse_backstory<'a>(input: &mut Input<'a>) -> PResult<&'a str> {
#[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"))]
#[cfg_attr(feature = "serde", serde(tag = "token", content = "content"))]
pub enum Token<'a> {
Metadata {
key: &'a str,
Expand Down Expand Up @@ -582,7 +582,19 @@ mod test {
let serialized = serde_json::to_string(&token).expect("failed to serialize");
assert_eq!(
serialized,
r#"{"token":"Ingredient","name":"quinoa","quantity":"200","unit":"gr"}"#
r#"{"token":"Ingredient","content":{"name":"quinoa","quantity":"200","unit":"gr"}}"#
);
}

#[test]
#[cfg(feature = "serde")]
fn test_token_serialization_creates_right_payload_single_string() {
let token = Token::Word("holis");

Check warning on line 592 in crates/recipe-parser/src/parser.rs

View workflow job for this annotation

GitHub Actions / cargo fmt

Diff in /home/runner/work/recipe-lang/recipe-lang/crates/recipe-parser/src/parser.rs

let serialized = serde_json::to_string(&token).expect("failed to serialize");
assert_eq!(
serialized,
r#"{"token":"Word","content":"holis"}"#
);
}

Expand Down

0 comments on commit 276a282

Please sign in to comment.