def to_event_message(cls, event: BaseEvent) -> Message: # FIXME Should one of `aggregate_cls` or `stream_name` be mandatory? if not (event.meta_.aggregate_cls or event.meta_.stream_name): raise IncorrectUsageError({ "_entity": [ f"Event `{event.__class__.__name__}` needs to be associated with an aggregate or a stream" ] }) if has_id_field(event): identifier = getattr(event, id_field(event).field_name) else: identifier = str(uuid4()) # Use explicit stream name if provided, or fallback on Aggregate's stream name stream_name = (event.meta_.stream_name or event.meta_.aggregate_cls.meta_.stream_name) return cls( stream_name=f"{stream_name}-{identifier}", type=fully_qualified_name(event.__class__), data=event.to_dict(), metadata=MessageMetadata( kind=MessageType.EVENT.value, owner=current_domain.domain_name, **cls.derived_metadata(MessageType.EVENT.value), ) # schema_version=command.meta_.version, # FIXME Maintain version for event )
def to_command_message(cls, command: BaseCommand) -> Message: # FIXME Should one of `aggregate_cls` or `stream_name` be mandatory? if not (command.meta_.aggregate_cls or command.meta_.stream_name): raise IncorrectUsageError({ "_entity": [ f"Command `{command.__class__.__name__}` needs to be associated with an aggregate or a stream" ] }) # Use the value of an identifier field if specified, or generate a new uuid if has_id_field(command): identifier = getattr(command, id_field(command).field_name) else: identifier = str(uuid4()) # Use explicit stream name if provided, or fallback on Aggregate's stream name stream_name = (command.meta_.stream_name or command.meta_.aggregate_cls.meta_.stream_name) return cls( stream_name=f"{stream_name}:command-{identifier}", type=fully_qualified_name(command.__class__), data=command.to_dict(), metadata=MessageMetadata( kind=MessageType.COMMAND.value, owner=current_domain.domain_name, **cls.derived_metadata(MessageType.COMMAND.value), ) # schema_version=command.meta_.version, # FIXME Maintain version for command )
def test_id_field_for_command_with_identifier(): assert has_id_field(Registered) is True field = id_field(Registered) assert field is not None assert field.field_name == "user_id"
def test_id_field_for_command_without_identifier(): assert has_id_field(EmailSent) is False
def test_elements_with_optional_id_field(): assert has_id_field(CommandWithId) is True assert has_id_field(CommandWithoutId) is False
def test_elements_with_no_id_fields(): assert has_id_field(ApplicationService1) is False
def test_elements_with_id_fields(): assert has_id_field(Entity1) is True assert has_id_field(Aggregate1) is True