diff --git a/common/birdxplorer_common/models.py b/common/birdxplorer_common/models.py index 0e9801f..2a81b67 100644 --- a/common/birdxplorer_common/models.py +++ b/common/birdxplorer_common/models.py @@ -21,12 +21,14 @@ from pydantic import Field as PydanticField from pydantic import ( GetCoreSchemaHandler, + GetJsonSchemaHandler, HttpUrl, TypeAdapter, computed_field, model_validator, ) from pydantic.alias_generators import to_camel +from pydantic.json_schema import JsonSchemaValue from pydantic.main import IncEx from pydantic_core import core_schema @@ -741,11 +743,30 @@ def from_url(cls, url: HttpUrl) -> "LinkId": @classmethod def __get_pydantic_core_schema__(cls, _source_type: Any, _handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: - return core_schema.no_info_plain_validator_function( - cls.validate, - serialization=core_schema.plain_serializer_function_ser_schema(cls.serialize, when_used="json"), + return core_schema.union_schema( + [ + core_schema.is_instance_schema(cls), + core_schema.no_info_plain_validator_function(cls.validate), + ], + serialization=core_schema.plain_serializer_function_ser_schema( + cls.serialize, info_arg=False, when_used="json" + ), ) + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + json_schema = handler(core_schema) + json_schema = handler.resolve_ref_schema(json_schema) + # __get_pydantic_core_schema__ に is_instance_schema を追加したが、 + # APIから返却する際の実態は string (uuid) のみである + # この差分により、openapi specを自動生成する際に不要な anyOf: [] が生成されてしまうのを抑制する + del json_schema["anyOf"] + json_schema["type"] = "string" + json_schema["format"] = "uuid" + return json_schema + @classmethod def validate(cls, v: Any) -> "LinkId": return cls(v)