Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"additionalProperties: false" for struct annotated with serde "#[serde(deny_unknown_fields)]" #30

Merged
merged 1 commit into from
May 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions schemars/tests/expected/struct-normal-additional-properties.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Struct",
"type": "object",
"additionalProperties": false,
"required": [
"bar",
"foo"
],
"properties": {
"bar": {
"type": "boolean"
},
"baz": {
"type": [
"string",
"null"
]
},
"foo": {
"type": "integer",
"format": "int32"
}
}
}
16 changes: 16 additions & 0 deletions schemars/tests/struct_additional_properties.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
mod util;
use schemars::JsonSchema;
use util::*;

#[derive(Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Struct {
foo: i32,
bar: bool,
baz: Option<String>,
}

#[test]
fn struct_normal_additional_properties() -> TestResult {
test_default_generated_schema::<Struct>("struct-normal-additional-properties")
}
3 changes: 1 addition & 2 deletions schemars_derive/src/attr/schemars_to_serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ use syn::{Attribute, Data, Field, Meta, NestedMeta, Variant};
static SERDE_KEYWORDS: &[&str] = &[
"rename",
"rename_all",
// TODO: for structs with `deny_unknown_fields`, set schema's `additionalProperties` to false.
// "deny_unknown_fields",
"deny_unknown_fields",
"tag",
"content",
"untagged",
Expand Down
11 changes: 11 additions & 0 deletions schemars_derive/src/schema_exprs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,22 @@ fn expr_for_struct(fields: &[Field], cattrs: Option<&serde_attr::Container>) ->
}
});

let deny_unknown_fields = cattrs
.map_or(false, |attrs| attrs.deny_unknown_fields());

quote! {
{
#set_container_default
let mut schema_object = schemars::schema::SchemaObject {
instance_type: Some(schemars::schema::InstanceType::Object.into()),
object: Some(Box::new(schemars::schema::ObjectValidation {
additional_properties: if #deny_unknown_fields {
Some(Box::new(false.into()))
} else {
None
},
..Default::default()
})),
..Default::default()
};
#(#properties)*
Expand Down