Skip to content

Commit

Permalink
Merge pull request #124 from codeforjapan/issue-123-linkid-pydantic-c…
Browse files Browse the repository at this point in the history
…ompat

LinkIdのpydantic互換性を改善する
  • Loading branch information
yu23ki14 authored Oct 24, 2024
2 parents b147a78 + e77fe1b commit 2340664
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions common/birdxplorer_common/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 2340664

Please sign in to comment.