Skip to content

Commit

Permalink
simplify generated code for validating object properties
Browse files Browse the repository at this point in the history
  • Loading branch information
icewind1991 authored and GREsau committed May 5, 2024
1 parent ea1a381 commit 541e422
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
11 changes: 10 additions & 1 deletion schemars/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ JSON Schema types.

#[cfg(feature = "impl_json_schema")]
use crate as schemars;
#[cfg(feature = "impl_json_schema")]
use crate::JsonSchema;
use crate::{Map, Set};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -535,6 +534,16 @@ pub struct ObjectValidation {
pub property_names: Option<Box<Schema>>,
}

impl ObjectValidation {
pub fn insert_property<T: ?Sized + JsonSchema>(&mut self, key: &str, mut has_default: bool, required: bool, schema: Schema) {
self.properties.insert(key.to_owned(), schema);
has_default |= T::_schemars_private_is_option();
if required || !has_default {
self.required.insert(key.to_owned());
}
}
}

/// The possible types of values in JSON Schema documents.
///
/// See [JSON Schema 4.2.1. Instance Data Model](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-4.2.1).
Expand Down
18 changes: 3 additions & 15 deletions schemars_derive/src/schema_exprs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,19 +497,8 @@ fn expr_for_struct(

let (ty, type_def) = type_for_field_schema(field);

let maybe_insert_required = match (&default, field.validation_attrs.required()) {
(Some(_), _) => TokenStream::new(),
(None, false) => {
quote! {
if !<#ty as schemars::JsonSchema>::_schemars_private_is_option() {
object_validation.required.insert(#name.to_owned());
}
}
}
(None, true) => quote! {
object_validation.required.insert(#name.to_owned());
},
};
let has_default = default.is_some();
let required = field.validation_attrs.required();

let metadata = SchemaMetadata {
read_only: field.serde_attrs.skip_deserializing(),
Expand All @@ -535,8 +524,7 @@ fn expr_for_struct(
quote! {
{
#type_def
object_validation.properties.insert(#name.to_owned(), #schema_expr);
#maybe_insert_required
object_validation.insert_property::<#ty>(#name, #has_default, #required, #schema_expr);
}
}
})
Expand Down

0 comments on commit 541e422

Please sign in to comment.