alice-biometrics / petisco

🍪 petisco is a framework for helping Python developers to build clean Applications

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Improve typing on DomainEvents and Commands retrieved from RabbitMQ consumers

acostapazo opened this issue · comments

Description

When a RabbitMQConsumer is used with some subscriber, is necessary define the DomainEvent with the subscribed_to. However, in the handle we're receiving a generic DomainEvent.

from petisco import DomainEvent, DomainEventSubscriber
from meiga import isSuccess

class MyDomainEvent(DomainEvent):
      my_specific_value: str

class MyDomainEventSubscriber(DomainEventSubscriber):

      def subscribed_to(self) -> list[type[DomainEvent]]:
          return [MyDomainEvent]

      def handle(self, domain_event: DomainEvent) -> BoolResult:
         # Add your use case here
         return isSuccess # sends an ack to the queue

subscribers = [MyDomainEventSubscriber]
consumer = RabbitMqMessageConsumerMother.default()
consumer.add_subscribers(subscribers)
consumer.start()

This is ok and functional, but a little bit annoying if you want to access to an specific attribute of your DomainEvent (in this case MyDomainEvent)

This will fail as received domain_event is a generic DomainEvent:

class MyDomainEventSubscriber(DomainEventSubscriber):

      def subscribed_to(self) -> list[type[DomainEvent]]:
          return [MyDomainEvent]

      def handle(self, domain_event: DomainEvent) -> BoolResult:
         my_specific_value = domain_event. my_specific_value # <----- THIS WILL FAIL
         return isSuccess 

You have to access via attributes

my_specific_value = domain_event. attributes.get("my_specific_value")

Wanted Solution

It would be fantastic if received domain event is already transformed to an specific value.

class MyDomainEventSubscriber(DomainEventSubscriber):

      def subscribed_to(self) -> list[type[DomainEvent]]:
          return [MyDomainEvent]

      def handle(self, domain_event: MyDomainEvent) -> BoolResult:
         my_specific_value = domain_event. my_specific_value # <----- 
         return isSuccess 

Questions

What happens if the subscriber is subscribed to several types? 🤔