I am creating an application using hexagonal architecture. The application uses WebSocket connections to communicate with some outside clients. Communication works in both ways. the client can send a WebSocket message which the application needs to handle and the application can also send a WebSocket message to the client.
According to hexagonal architecture, an application service implements a port used by the driving adapter. Whereas, an application service uses the port implemented by a driven adapter. This will help me easily replace an old implementation with a new one by providing a new implementation for port (on the driving side) or adapter (on the driven side).
In my case of WebSocket communication, the WebSocket port acts both as the driving port (to handle messages coming from the actor) and the driven port (to send messages to the actor).
I am quite confused about how to solve this problem while sticking to the hexagonal architecture.
3
There is no problem. It is okay that the web socket service is both driving and driven.
Let’s see an example.
- You have a web shop where backend and frontend communicate via web socket.
- When the user clicks on the buy button in the frontend, the backend needs to execute the according business logic.
- When the backend detects that there are new items available, the frontend shoud display some message.
Using hexagonal architecture, the backend needs a BuyItemPort and a PushMessagePort.
Buying an item is business logic. Therefore, the BuyItemPort is implemented in the application layer. When the user clicks on the buy button, the frontend sends a message via web socket. It arrives on the web socket service in the backend, which calls the BuyItemPort. Therefore, the web socket service must be a driving adapter.
It is business logic that a push message should be sent when there are new items in the store. So there is some kind of NewItem event with an event handler in the application layer. The handler now calls the PushMessagePort, which sends the message via web socket to the frontend. Therefore, the web socket service must be a driven adapter.
1