Skip to content

Commit

Permalink
Implement JsonSchemaAs for OneOrMany instead of JsonSchema
Browse files Browse the repository at this point in the history
Currently, there is an `impl JsonSchema for WrapSchema<OneOrMany<...>>`.
This works fine if you only directly need `OneOrMany` but causes errors
if you want to nest it (e.g. `Option<OneOrMany<_>>`).

This PR changes the impl to a `JsonSchemaAs` impl, which is the correct
approach. I think I just missed these ones during a rebase. In any case,
the change should be fully backwards compatible due to the blanket
schema impl.

I have added a snapshot test. The actual snapshot doesn't matter - the
real test is that the struct below compiles

    #[serde_as]
    #[derive(Serialize, Deserialize, JsonSchema)]
    struct Test {
	#[serde_as(as = "Option<OneOrMany<_>>")]
	optional_vec: Option<Vec<String>>,
    }
  • Loading branch information
swlynch99 committed Jun 28, 2024
1 parent f74b460 commit dee706a
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 4 deletions.
8 changes: 4 additions & 4 deletions serde_with/src/schemars_0_8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -794,9 +794,9 @@ map_first_last_wins_schema!(=> S indexmap_1::IndexMap<K, V, S>);
#[cfg(feature = "indexmap_2")]
map_first_last_wins_schema!(=> S indexmap_2::IndexMap<K, V, S>);

impl<T, TA> JsonSchema for WrapSchema<Vec<T>, OneOrMany<TA, PreferOne>>
impl<T, TA> JsonSchemaAs<Vec<T>> for OneOrMany<TA, PreferOne>
where
WrapSchema<T, TA>: JsonSchema,
TA: JsonSchemaAs<T>,
{
fn schema_name() -> String {
std::format!(
Expand Down Expand Up @@ -835,9 +835,9 @@ where
}
}

impl<T, TA> JsonSchema for WrapSchema<Vec<T>, OneOrMany<TA, PreferMany>>
impl<T, TA> JsonSchemaAs<Vec<T>> for OneOrMany<TA, PreferMany>
where
WrapSchema<T, TA>: JsonSchema,
TA: JsonSchemaAs<T>,
{
fn schema_name() -> String {
std::format!(
Expand Down
7 changes: 7 additions & 0 deletions serde_with/tests/schemars_0_8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,13 @@ mod snapshots {
value: u32
}
}

one_or_many_nested {
struct Test {
#[serde_as(as = "Option<OneOrMany<_>>")]
optional_many: Option<Vec<String>>,
}
}
}
}

Expand Down
33 changes: 33 additions & 0 deletions serde_with/tests/schemars_0_8/snapshots/one_or_many_nested.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Test",
"type": "object",
"properties": {
"optional_many": {
"default": null,
"anyOf": [
{
"$ref": "#/definitions/OneOrMany<String, PreferOne>"
},
{
"type": "null"
}
]
}
},
"definitions": {
"OneOrMany<String, PreferOne>": {
"anyOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
}
}
}

0 comments on commit dee706a

Please sign in to comment.