"""Basic usage examples for ATProto data and lexicon modules.""" import json from atpasser.data import serializer, CIDLink, DateTimeString from atpasser.lexicon import parser, registry def demonstrate_data_serialization(): """Demonstrate basic data serialization.""" print("=== Data Serialization Demo ===") # Create some sample data sample_data = { "title": "Hello ATProto", "content": "This is a test post", "createdAt": "2024-01-15T10:30:00.000Z", "tags": ["atproto", "test", "demo"], "cidLink": CIDLink( "bafyreidfayvfuwqa7qlnopdjiqrxzs6blmoeu4rujcjtnci5beludirz2a" ), } # Serialize to JSON json_output = serializer.to_json(sample_data, indent=2) print("JSON Output:") print(json_output) # Deserialize back deserialized = serializer.from_json(json_output) print("\nDeserialized:") print(deserialized) print() def demonstrate_lexicon_parsing(): """Demonstrate Lexicon parsing.""" print("=== Lexicon Parsing Demo ===") # Sample Lexicon definition sample_lexicon = { "lexicon": 1, "id": "com.example.blog.post", "description": "A simple blog post record", "defs": { "main": { "type": "record", "key": "literal:post", "record": { "type": "object", "properties": { "title": {"type": "string", "maxLength": 300}, "content": {"type": "string"}, "createdAt": {"type": "string", "format": "datetime"}, "tags": { "type": "array", "items": {"type": "string"}, "maxLength": 10, }, }, "required": ["title", "content", "createdAt"], }, } }, } try: # Parse and register the Lexicon parser.parse_and_register(sample_lexicon) print("Lexicon parsed and registered successfully!") # Get the generated model model_class = registry.get_model("com.example.blog.post") if model_class: print(f"Generated model: {model_class.__name__}") # Create an instance using the model post_data = { "title": "Test Post", "content": "This is a test post content", "createdAt": "2024-01-15T10:30:00.000Z", "tags": ["test", "demo"], } validated_post = model_class(**post_data) print(f"Validated post: {validated_post.model_dump()}") except Exception as e: print(f"Error: {e}") print() def demonstrate_custom_types(): """Demonstrate custom type validation.""" print("=== Custom Type Validation Demo ===") # DateTimeString validation try: valid_dt = DateTimeString("2024-01-15T10:30:00.000Z") print(f"Valid datetime: {valid_dt}") except Exception as e: print(f"DateTime validation error: {e}") # Invalid datetime try: invalid_dt = DateTimeString("invalid-date") print(f"Invalid datetime: {invalid_dt}") except Exception as e: print(f"DateTime validation caught: {e}") print() if __name__ == "__main__": demonstrate_data_serialization() demonstrate_lexicon_parsing() demonstrate_custom_types() print("Demo completed!")