Skip to content

Commit

Permalink
Update doc comments and make SchemaGenerator available from crate root
Browse files Browse the repository at this point in the history
  • Loading branch information
GREsau committed May 27, 2024
1 parent fb6e1a5 commit 760403e
Show file tree
Hide file tree
Showing 13 changed files with 150 additions and 74 deletions.
38 changes: 19 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,9 @@ println!("{}", serde_json::to_string_pretty(&schema).unwrap());

```json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "MyStruct",
"type": "object",
"required": ["my_bool", "my_int"],
"properties": {
"my_bool": {
"type": "boolean"
Expand All @@ -51,34 +50,33 @@ println!("{}", serde_json::to_string_pretty(&schema).unwrap());
"my_nullable_enum": {
"anyOf": [
{
"$ref": "#/definitions/MyEnum"
"$ref": "#/$defs/MyEnum"
},
{
"type": "null"
}
]
}
},
"definitions": {
"required": ["my_int", "my_bool"],
"$defs": {
"MyEnum": {
"anyOf": [
"oneOf": [
{
"type": "object",
"required": ["StringNewType"],
"properties": {
"StringNewType": {
"type": "string"
}
},
"additionalProperties": false
"additionalProperties": false,
"required": ["StringNewType"]
},
{
"type": "object",
"required": ["StructVariant"],
"properties": {
"StructVariant": {
"type": "object",
"required": ["floats"],
"properties": {
"floats": {
"type": "array",
Expand All @@ -87,10 +85,12 @@ println!("{}", serde_json::to_string_pretty(&schema).unwrap());
"format": "float"
}
}
}
},
"required": ["floats"]
}
},
"additionalProperties": false
"additionalProperties": false,
"required": ["StructVariant"]
}
]
}
Expand Down Expand Up @@ -134,40 +134,39 @@ println!("{}", serde_json::to_string_pretty(&schema).unwrap());

```json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "MyStruct",
"type": "object",
"required": ["myBool", "myNumber"],
"properties": {
"myBool": {
"type": "boolean"
},
"myNullableEnum": {
"default": null,
"anyOf": [
{
"$ref": "#/definitions/MyEnum"
"$ref": "#/$defs/MyEnum"
},
{
"type": "null"
}
]
],
"default": null
},
"myNumber": {
"type": "integer",
"format": "int32"
}
},
"additionalProperties": false,
"definitions": {
"required": ["myNumber", "myBool"],
"$defs": {
"MyEnum": {
"anyOf": [
{
"type": "string"
},
{
"type": "object",
"required": ["floats"],
"properties": {
"floats": {
"type": "array",
Expand All @@ -176,7 +175,8 @@ println!("{}", serde_json::to_string_pretty(&schema).unwrap());
"format": "float"
}
}
}
},
"required": ["floats"]
}
]
}
Expand Down
3 changes: 1 addition & 2 deletions docs/_includes/examples/custom_serialization.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use schemars::Schema;
use schemars::{gen::SchemaGenerator, schema_for, JsonSchema};
use schemars::{schema_for, JsonSchema, Schema, SchemaGenerator};
use serde::{Deserialize, Serialize};

// `int_as_string` and `bool_as_string` use the schema for `String`.
Expand Down
3 changes: 1 addition & 2 deletions schemars/examples/custom_serialization.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use schemars::Schema;
use schemars::{gen::SchemaGenerator, schema_for, JsonSchema};
use schemars::{schema_for, JsonSchema, Schema, SchemaGenerator};
use serde::{Deserialize, Serialize};

// `int_as_string` and `bool_as_string` use the schema for `String`.
Expand Down
9 changes: 2 additions & 7 deletions schemars/src/_private.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
use crate::gen::SchemaGenerator;
use crate::JsonSchema;
use crate::Schema;
use crate::{JsonSchema, Schema, SchemaGenerator};
use serde::Serialize;
use serde_json::json;
use serde_json::map::Entry;
use serde_json::Map;
use serde_json::Value;
use serde_json::{json, map::Entry, Map, Value};

// Helper for generating schemas for flattened `Option` fields.
pub fn json_schema_for_flatten<T: ?Sized + JsonSchema>(
Expand Down
35 changes: 20 additions & 15 deletions schemars/src/gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ use crate::{visit::*, JsonSchema};
use dyn_clone::DynClone;
use serde::Serialize;
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::{any::Any, collections::HashSet, fmt::Debug};
use std::collections::{HashMap, HashSet};
use std::{any::Any, fmt::Debug};

type CowStr = std::borrow::Cow<'static, str>;

Expand All @@ -38,7 +38,7 @@ pub struct SchemaSettings {
///
/// A single leading `#` and/or single trailing `/` are ignored.
///
/// Defaults to `/$defs`.
/// Defaults to `"/$defs"`.
pub definitions_path: String,
/// The URI of the meta-schema describing the structure of the generated schemas.
///
Expand All @@ -55,6 +55,8 @@ pub struct SchemaSettings {
}

impl Default for SchemaSettings {
/// The default settings currently conform to [JSON Schema 2020-12](https://json-schema.org/specification-links#2020-12), but this is liable to change in a future version of Schemars if support for other JSON Schema versions is added.
/// If you rely on generated schemas conforming to draft 2020-12, consider using the [`SchemaSettings::draft2020_12()`] method.
fn default() -> SchemaSettings {
SchemaSettings::draft2020_12()
}
Expand Down Expand Up @@ -97,7 +99,7 @@ impl SchemaSettings {
}
}

/// Creates `SchemaSettings` that conform to [OpenAPI 3.0](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#schemaObject).
/// Creates `SchemaSettings` that conform to [OpenAPI 3.0](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#schema).
pub fn openapi3() -> SchemaSettings {
SchemaSettings {
option_nullable: true,
Expand Down Expand Up @@ -153,7 +155,7 @@ impl SchemaSettings {
///
/// # Example
/// ```
/// use schemars::{JsonSchema, gen::SchemaGenerator};
/// use schemars::{JsonSchema, SchemaGenerator};
///
/// #[derive(JsonSchema)]
/// struct MyStruct {
Expand Down Expand Up @@ -203,7 +205,7 @@ impl SchemaGenerator {
///
/// # Example
/// ```
/// use schemars::gen::SchemaGenerator;
/// use schemars::SchemaGenerator;
///
/// let gen = SchemaGenerator::default();
/// let settings = gen.settings();
Expand Down Expand Up @@ -287,7 +289,7 @@ impl SchemaGenerator {
}

/// Returns the collection of all [non-inlined](JsonSchema::always_inline_schema) schemas that have been generated,
/// leaving an empty map in its place.
/// leaving an empty `Map` in its place.
///
/// The keys of the returned `Map` are the [schema names](JsonSchema::schema_name), and the values are the schemas
/// themselves.
Expand All @@ -300,11 +302,10 @@ impl SchemaGenerator {
self.settings.visitors.iter_mut().map(|v| v.as_mut())
}

/// Generates a root JSON Schema for the type `T`.
/// Generates a JSON Schema for the type `T`.
///
/// If `T`'s schema depends on any [non-inlined](JsonSchema::always_inline_schema) schemas, then this method will
/// add them to the `SchemaGenerator`'s schema definitions and include them in the returned `SchemaObject`'s
/// [`definitions`](../schema/struct.Metadata.html#structfield.definitions)
/// include them in the returned `Schema` at the [definitions path](SchemaSettings::definitions_path) (by default `"$defs"`).
pub fn root_schema_for<T: ?Sized + JsonSchema>(&mut self) -> Schema {
let mut schema = self.json_schema_internal::<T>(T::schema_id());

Expand All @@ -324,10 +325,10 @@ impl SchemaGenerator {
schema
}

/// Consumes `self` and generates a root JSON Schema for the type `T`.
/// Consumes `self` and generates a JSON Schema for the type `T`.
///
/// If `T`'s schema depends on any [non-inlined](JsonSchema::always_inline_schema) schemas, then this method will
/// include them in the returned `SchemaObject`'s [`definitions`](../schema/struct.Metadata.html#structfield.definitions)
/// include them in the returned `Schema` at the [definitions path](SchemaSettings::definitions_path) (by default `"$defs"`).
pub fn into_root_schema_for<T: ?Sized + JsonSchema>(mut self) -> Schema {
let mut schema = self.json_schema_internal::<T>(T::schema_id());

Expand All @@ -348,10 +349,12 @@ impl SchemaGenerator {
schema
}

/// Generates a root JSON Schema for the given example value.
/// Generates a JSON Schema for the given example value.
///
/// If the value implements [`JsonSchema`](crate::JsonSchema), then prefer using the [`root_schema_for()`](Self::root_schema_for())
/// function which will generally produce a more precise schema, particularly when the value contains any enums.
///
/// If the `Serialize` implementation of the value decides to fail, this will return an [`Err`].
pub fn root_schema_for_value<T: ?Sized + Serialize>(
&mut self,
value: &T,
Expand All @@ -377,10 +380,12 @@ impl SchemaGenerator {
Ok(schema)
}

/// Consumes `self` and generates a root JSON Schema for the given example value.
/// Consumes `self` and generates a JSON Schema for the given example value.
///
/// If the value implements [`JsonSchema`](crate::JsonSchema), then prefer using the [`into_root_schema_for()!`](Self::into_root_schema_for())
/// function which will generally produce a more precise schema, particularly when the value contains any enums.
///
/// If the `Serialize` implementation of the value decides to fail, this will return an [`Err`].
pub fn into_root_schema_for_value<T: ?Sized + Serialize>(
mut self,
value: &T,
Expand Down Expand Up @@ -513,7 +518,7 @@ fn json_pointer_mut<'a>(
Some(object)
}

/// A [Visitor](Visitor) which implements additional traits required to be included in a [SchemaSettings].
/// A [Visitor] which implements additional traits required to be included in a [SchemaSettings].
///
/// You will rarely need to use this trait directly as it is automatically implemented for any type which implements all of:
/// - [`Visitor`]
Expand Down
23 changes: 15 additions & 8 deletions schemars/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ mod macros;
/// outside of `schemars`, and should not be considered part of the public API.
#[doc(hidden)]
pub mod _private;
/// Types for generating JSON schemas.
pub mod gen;
/// Types for recursively modifying JSON schemas.
pub mod visit;

#[cfg(feature = "schemars_derive")]
Expand All @@ -25,6 +27,7 @@ pub use schemars_derive::*;
#[doc(hidden)]
pub use serde_json as _serde_json;

pub use gen::SchemaGenerator;
pub use schema::Schema;

/// A type which can be described as a JSON Schema document.
Expand All @@ -50,7 +53,7 @@ pub use schema::Schema;
/// you will need to determine an appropriate name and ID for the type.
/// For non-generic types, the type name/path are suitable for this:
/// ```
/// use schemars::{gen::SchemaGenerator, Schema, JsonSchema};
/// use schemars::{SchemaGenerator, Schema, JsonSchema, json_schema};
/// use std::borrow::Cow;
///
/// struct NonGenericType;
Expand All @@ -67,7 +70,9 @@ pub use schema::Schema;
/// }
///
/// fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
/// todo!()
/// json_schema!({
/// "foo": "bar"
/// })
/// }
/// }
///
Expand All @@ -76,7 +81,7 @@ pub use schema::Schema;
///
/// But generic type parameters which may affect the generated schema should typically be included in the name/ID:
/// ```
/// use schemars::{gen::SchemaGenerator, Schema, JsonSchema};
/// use schemars::{SchemaGenerator, Schema, JsonSchema, json_schema};
/// use std::{borrow::Cow, marker::PhantomData};
///
/// struct GenericType<T>(PhantomData<T>);
Expand All @@ -95,7 +100,9 @@ pub use schema::Schema;
/// }
///
/// fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
/// todo!()
/// json_schema!({
/// "foo": "bar"
/// })
/// }
/// }
///
Expand Down Expand Up @@ -126,22 +133,22 @@ pub trait JsonSchema {
/// If two types produce different schemas, then they **must** have different `schema_id()`s,
/// but two types that produce identical schemas should *ideally* have the same `schema_id()`.
///
/// The default implementation returns the same value as `schema_name()`.
/// The default implementation returns the same value as [`schema_name()`](JsonSchema::schema_name).
fn schema_id() -> Cow<'static, str> {
Self::schema_name()
}

/// Generates a JSON Schema for this type.
///
/// If the returned schema depends on any [non-inlined](JsonSchema::always_inline_schema) schemas, then this method will
/// add them to the [`SchemaGenerator`](gen::SchemaGenerator)'s schema definitions.
/// add them to the [`SchemaGenerator`](SchemaGenerator)'s schema definitions.
///
/// This should not return a `$ref` schema.
fn json_schema(gen: &mut gen::SchemaGenerator) -> Schema;
fn json_schema(gen: &mut SchemaGenerator) -> Schema;

// TODO document and bring into public API?
#[doc(hidden)]
fn _schemars_private_non_optional_json_schema(gen: &mut gen::SchemaGenerator) -> Schema {
fn _schemars_private_non_optional_json_schema(gen: &mut SchemaGenerator) -> Schema {
Self::json_schema(gen)
}

Expand Down
Loading

0 comments on commit 760403e

Please sign in to comment.