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

Add support for custom JSON Schema instance formats defined by users #267

Merged
merged 4 commits into from
Nov 24, 2024

Conversation

Fatal1ty
Copy link
Owner

@Fatal1ty Fatal1ty commented Nov 24, 2024

This pull request updates the type annotation for the format field in the JSONSchema dataclass. The annotation is changed from JSONSchemaStringFormat | JSONSchemaInstanceFormatExtension to JSONSchemaInstanceFormat. This modification enables users to implement and utilize custom classes that inherit from JSONSchemaInstanceFormat.

The functionality provided by the pull request #232 can now be achieved using a plugin:

from typing import Annotated

from mashumaro.jsonschema import build_json_schema
from mashumaro.jsonschema.models import (
    Context,
    JSONSchema,
    JSONSchemaInstanceFormat,
)
from mashumaro.jsonschema.plugins import BasePlugin
from mashumaro.jsonschema.schema import Instance


class CustomJSONSchemaInstanceFormatPlugin(BasePlugin):
    def get_schema(
        self,
        instance: Instance,
        ctx: Context,
        schema: JSONSchema | None = None,
    ) -> JSONSchema | None:
        for annotation in instance.annotations:
            if isinstance(annotation, JSONSchemaInstanceFormat):
                schema.format = annotation
        return schema


class Custom1InstanceFormat(JSONSchemaInstanceFormat):
    CUSTOM1 = "custom1"


assert build_json_schema(
    Annotated[str, Custom1InstanceFormat.CUSTOM1],
    plugins=[CustomJSONSchemaInstanceFormatPlugin()],
).format is Custom1InstanceFormat.CUSTOM1

@Fatal1ty Fatal1ty merged commit 19d4642 into master Nov 24, 2024
30 checks passed
@Fatal1ty Fatal1ty deleted the custom-json-schema-instance-formats branch November 24, 2024 16:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant