3

I am trying to implement CQRS for the first time, and have an issue where I am receiving data from an external system which has a field which is a string reference, for example, username. I need to get the ID that the reference relates to, and reject if that ID isn't found.

The ID is from a separate bounded-context, and would seem inefficient to load the entire record to just get the ID. I was wondering if there was a CQRS pattern compliant way of returning just an ID based on a name/reference from the Command side, as it would seem like more of a Query concern (but maybe I'm being a bit naive?)

Steven Brookes
  • 834
  • 6
  • 27
  • This question reminds me of two somewhat related ones that I first had when I started learning and trying to apply DDD. https://stackoverflow.com/questions/5374176/can-ddd-repositories-be-aware-of-user-context https://stackoverflow.com/questions/5454521/accessing-data-for-validation-and-determining-default-values-using-ddd – jpierson Jan 18 '18 at 11:59

1 Answers1

1

I don't think there would be any query concern in this. The Query Side in CQRS is primarily for the read clients but that doesn't mean you cannot query at all internally on the command side. It's absolutely OK to receive a request, query some data (like events from event store/ message queue or any other kind of data) and take some action (like raising an event or not) based on that data. In fact, the whole idea of Event Sourcing relies on querying the old events and rehydrating the current state of an aggregate.

Another approach instead of querying could be that you can subscribe to the events raised by the other bounded-context and particularly subscribe to the event which contains ID of the reference and maintain a list of all the ID-username pairs in the first service.

Kanishk
  • 401
  • 3
  • 6
  • So i'd be OK to have a repository method on the command stack for GetIdByReference, for example? – Steven Brookes Jan 18 '18 at 10:33
  • 1
    The important point in my mind is that data within the aggregate governed by the command is part of an atomic transactional unit. Any data that you depend upon outside of that aggregate is is potentially inconsistent in terms of versioning (could be stale). As long as that's ok then the approach I'm familiar is to inject a separate service into you command handler that provides access to the necessary data, otherwise require the data as part of the provided command and pull it in within the Application Layer. – jpierson Jan 18 '18 at 12:06
  • @StevenBrookes: Yes that should be fine. Repository method would work but once your decision logic starts getting complicated or it starts depending on multiple services then you can consider using patterns like Sagas/ Process Managers. See this [link](https://stackoverflow.com/questions/48064987/check-command-for-validity-with-data-from-other-aggregate/48066601#48066601) – Kanishk Jan 18 '18 at 18:17