Skip to content

Commit

Permalink
add partial date type
Browse files Browse the repository at this point in the history
  • Loading branch information
carolinscholl committed Feb 21, 2024
1 parent 417250d commit dedd37a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
2 changes: 2 additions & 0 deletions mex/common/types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
VocabularyLoader,
split_to_caps,
)
from mex.common.types.year_month import YearMonth

__all__ = (
"AccessPlatformID",
Expand Down Expand Up @@ -90,4 +91,5 @@
"VocabularyEnum",
"VocabularyLoader",
"WorkPath",
"YearMonth",
)
27 changes: 27 additions & 0 deletions mex/common/types/year_month.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from typing import Any, Type

from pydantic import GetJsonSchemaHandler
from pydantic.json_schema import JsonSchemaValue
from pydantic_core import core_schema

YEAR_MONTH_PATTERN = r"^\d{4}(-\d{2})?$"


class YearMonth(str):
"""Partial date pattern that accepts YYYY or YYYY-MM format."""

@classmethod
def __get_pydantic_core_schema__(cls, _source: Type[Any]) -> core_schema.CoreSchema:
"""Get pydantic core schema."""
return core_schema.str_schema(pattern=YEAR_MONTH_PATTERN)

@classmethod
def __get_pydantic_json_schema__(
cls, core_schema_: core_schema.CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
"""Add title and format."""
field_schema = handler(core_schema_)
field_schema = handler.resolve_ref_schema(field_schema)
field_schema["title"] = cls.__name__
field_schema["examples"] = ["2024", "1999-04"]
return field_schema

0 comments on commit dedd37a

Please sign in to comment.