Skip to content

Commit

Permalink
refactor: enhance schema validation and property formatting in Notion…
Browse files Browse the repository at this point in the history
… automation

- Added validation to ensure schema properties are either a list or dictionary in `parse_schema`.
- Implemented checks for missing 'property_type' in property configurations.
- Updated `SchemaConfig` to validate properties and convert them to `PropertyConfig` if necessary.
- Enhanced `_format_entry_property` method to handle string properties and validate property formats.
- Improved `get_database` method to extract plain text from title arrays in the response.
  • Loading branch information
atxtechbro committed Dec 22, 2024
1 parent 37becc4 commit 269c34c
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 11 deletions.
10 changes: 9 additions & 1 deletion notion_automation/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ def parse_schema(schema_data):
"""Parse schema data into properties."""
properties = {}

if not isinstance(schema_data["properties"], (list, dict)):
raise ValueError("Properties must be a list or dictionary")

if isinstance(schema_data["properties"], list):
# Natural language or list format
for prop in schema_data["properties"]:
Expand Down Expand Up @@ -166,7 +169,12 @@ def parse_schema(schema_data):
else:
# Dictionary format
for name, config in schema_data["properties"].items():
properties[name] = PropertyConfig(**config)
if "property_type" not in config:
raise ValueError(f"Property '{name}' is missing 'property_type'")
properties[name] = PropertyConfig(
property_type=config["property_type"],
options=[PropertyOption(**opt) for opt in config.get("options", [])]
)

return properties

Expand Down
12 changes: 12 additions & 0 deletions notion_automation/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ class SchemaConfig:
title: str
properties: Dict[str, PropertyConfig]

def __post_init__(self):
"""Validate and convert properties if needed."""
if not isinstance(self.properties, dict):
raise ValueError("Properties must be a dictionary")

# Convert any dict properties to PropertyConfig
for name, prop in self.properties.items():
if isinstance(prop, dict):
self.properties[name] = PropertyConfig(**prop)
elif not isinstance(prop, PropertyConfig):
raise ValueError(f"Invalid property type for {name}")

@dataclass
class TaskProperty:
value: str
Expand Down
24 changes: 14 additions & 10 deletions notion_automation/notion_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,14 @@ def _format_entry_properties(self, properties):
return formatted

def _format_entry_property(self, prop):
"""Format a property value for the Notion API."""
if isinstance(prop, str):
# Handle direct string values
return {"rich_text": [{"text": {"content": prop}}]}

if not hasattr(prop, 'type'):
raise ValueError(f"Invalid property format: {prop}")

if prop.type == "title":
return {"title": [{"text": {"content": prop.value}}]}
elif prop.type == "rich_text":
Expand All @@ -134,17 +142,10 @@ def _format_entry_property(self, prop):
elif prop.type == "date":
return {"date": {"start": prop.value}}
else:
raise ValueError(f"Unsupported property type: {prop.type}")
raise ValueError(f"Unsupported property type: {prop.type}")

def get_database(self, database_id):
"""Retrieve database schema from Notion.
Args:
database_id (str): ID of the database to retrieve
Returns:
dict: Database schema information
"""
"""Retrieve database schema from Notion."""
url = f"{self.base_url}/databases/{database_id}"
response = requests.get(url, headers=self.headers)

Expand All @@ -153,4 +154,7 @@ def get_database(self, database_id):
logger.error(f"Response body: {response.text}")
response.raise_for_status()

return response.json()
data = response.json()
# Extract plain text from title array
data["title"] = data["title"][0]["plain_text"] if data["title"] else ""
return data

0 comments on commit 269c34c

Please sign in to comment.