pub struct SchemaRegistry { /* private fields */ }Expand description
Registry for collecting and deduplicating JSON schemas.
The SchemaRegistry tracks schemas by name and returns $ref references
when a schema is already registered. This prevents schema duplication
in OpenAPI documents.
§Example
use fastapi_openapi::{SchemaRegistry, JsonSchema, Schema};
#[derive(JsonSchema)]
struct User {
id: i64,
name: String,
}
let registry = SchemaRegistry::new();
// First access registers the schema and returns a $ref
let schema1 = User::schema_with_registry(®istry);
assert!(matches!(schema1, Schema::Ref(_)));
// Second access returns the same $ref without re-registering
let schema2 = User::schema_with_registry(®istry);
assert!(matches!(schema2, Schema::Ref(_)));
// Export all collected schemas for components/schemas
let schemas = registry.into_schemas();
assert!(schemas.contains_key("User"));Implementations§
Source§impl SchemaRegistry
impl SchemaRegistry
Sourcepub fn get_or_register<T: JsonSchema>(&self, name: &str) -> Schema
pub fn get_or_register<T: JsonSchema>(&self, name: &str) -> Schema
Get or register a schema by name.
If the schema is already registered, returns a $ref reference.
Otherwise, generates the schema, registers it, and returns a $ref.
Sourcepub fn register(&self, name: impl Into<String>, schema: Schema) -> Schema
pub fn register(&self, name: impl Into<String>, schema: Schema) -> Schema
Register a schema directly by name.
Returns a $ref to the registered schema.
Sourcepub fn contains(&self, name: &str) -> bool
pub fn contains(&self, name: &str) -> bool
Check if a schema with the given name is already registered.
Sourcepub fn into_schemas(self) -> HashMap<String, Schema>
pub fn into_schemas(self) -> HashMap<String, Schema>
Consume the registry and return all collected schemas.
The returned map is suitable for use in components.schemas.
Sourcepub fn schemas(&self) -> HashMap<String, Schema>
pub fn schemas(&self) -> HashMap<String, Schema>
Get a clone of all registered schemas without consuming the registry.
Sourcepub fn merge(&self, other: &SchemaRegistry)
pub fn merge(&self, other: &SchemaRegistry)
Merge another registry’s schemas into this one.
If a schema with the same name exists in both, the existing one is kept.