Chapter 10. Commands and Command Handler
In the previous chapter, we talked about using events as a way of representing the inputs to our system, and we turned our application into a message-processing machine.
To achieve that, we converted all our use-case functions to event handlers.
When the API receives a POST to create a new batch, it builds a new BatchCreated
event and handles it as if it were an internal event.
This might feel counterintuitive. After all, the batch hasn’t been
created yet; that’s why we called the API. We’re going to fix that conceptual
wart by introducing commands and showing how they can be handled by the same
message bus but with slightly different rules.
Tip
The code for this chapter is in the chapter_10_commands branch on GitHub:
git clone https://github.com/cosmicpython/code.git cd code git checkout chapter_10_commands # or to code along, checkout the previous chapter: git checkout chapter_09_all_messagebus
Commands and Events
Like events, commands are a type of message—instructions sent by one part of a system to another. We usually represent commands with dumb data structures and can handle them in much the same way as events.
The differences between commands and events, though, are important.
Commands are sent by one actor to another specific actor with the expectation that a particular thing will happen as a result. When we post a form to an API handler, we are sending a command. We name commands with imperative mood verb phrases like “allocate ...