Skip to content

Commit

Permalink
Merge pull request #26 from reworkd/date-and-datetime-types
Browse files Browse the repository at this point in the history
Date validation
  • Loading branch information
asim-shrestha authored May 29, 2024
2 parents 58a16af + 6393516 commit 8715945
Show file tree
Hide file tree
Showing 5 changed files with 529 additions and 280 deletions.
5 changes: 3 additions & 2 deletions harambe/parser/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
from pydantic import BaseModel, create_model, Field, Extra, ValidationError
from typing import Any, Dict, List, Optional, Type

from harambe.types import Schema, URL
from harambe.parser.type_date import ParserTypeDate
from harambe.parser.type_url import ParserTypeUrl
from harambe.types import Schema, URL


OBJECT_TYPE = "object"
Expand Down Expand Up @@ -48,7 +49,7 @@ def __init__(self, schema: Schema):
"double": float,
LIST_TYPE: List,
OBJECT_TYPE: Dict[str, Any],
# TODO: Add support for date and datetime types
"date": ParserTypeDate(),
"url": ParserTypeUrl(),
}

Expand Down
29 changes: 29 additions & 0 deletions harambe/parser/type_date.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from pydantic.functional_validators import AfterValidator
from typing_extensions import Annotated

import dateparser


class ParserTypeDate:
def __new__(self):
return Annotated[str, AfterValidator(self.validate)]

def validate(date: str):
if not isinstance(date, str):
raise ValueError("Wrong input type")

# Trim whitespaces
date = date.strip()

# Make sure it's not empty string
if len(date) == 0:
raise ValueError("Empty input")

# Attempt to parse date string
try:
dateparser.parse(date)
return date
except ValueError:
pass

raise ValueError(f"Unable to parse input as date: {date}")
Loading

0 comments on commit 8715945

Please sign in to comment.