peefartpoop
peefartpoop

Reputation: 133

Is there a way to combine a query and a command in CQRS?

I have a project built using CQRS, but I can't figure out how to implement one use case.

The user needs to be able to make a Query which will return a set of data for them to view. However, I also need to save the data they got at the same time.

Is there a way to do this within a Query without violating CQRS' principles? Or would the Query and Command need to be two separate API calls one after another?

Upvotes: 1

Views: 1071

Answers (3)

Roman Eremin
Roman Eremin

Reputation: 1451

In CQRS it is your client who can do both command and queries. This client is not necessary a piece of UI.

It can be an API endpoint handler, which would

  • receive a query
  • forward it to the query endpoint
  • wait for the answer
  • send an answer to the caller
  • send a command to store the answer

Upvotes: 1

Eben Roux
Eben Roux

Reputation: 13246

As @VoiceOfUnreason stated, it may be somewhat strange to effect domain changes when querying data.

However, it may be that you could swop that around.

For instance, perhaps one could query a forecast of sorts. We would want to store that forecast. It then seems as though the query results in us having to save the result. This appears to break CQS at some level since each query would result in a change of state.

If we swop that around and first request a forecast via the domain handling and then that produces a result, or even a pointer to the result, then the query would be something you could perform on the data multiple times without "breaking" CQS.

Upvotes: 0

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57239

Is there a way to do this within a Query without violating CQRS' principles?

It depends.

If "save the data" means "make some change to the domain model"... well, that would be pretty weird.

Asking a question should not change the answer. -- Bertrand Meyer

On the other hand, logging/telemetry are pretty normal ways to track the activity of an application, so that should be fine.

There are some realities of a distributed system on an unreliable network that you need to be aware of (what should the behavior be if the telemetry system is not available? What are the consequences of recording queries that don't actually reach the client (because the network is unreliable).

Upvotes: 0

Related Questions