Writing Middleware
A ChatAlly application consists of one or more servers that connect the application to external clients, like WhatsApp, Signal or websockets, and middleware. The middleware is responsible for processing the request from any server and eventually generating a response. The work can be shared between all the middleware modules.
Execution context
All middleware modules are provided with an application context. The context contains the incoming request and a response object, that can be used to transmit outgoing messages.
See the reference documentation for details.
async, await next() and execution order
All modules are executed in order. Modules can be synchronous or asynchronous and will be awaited by the application before continuing with the next module.
In the upstream leg of the processing pipeline you could add middleware that analyzes the request or prepares data and puts it into the processing context. You could then add some middleware that manages the dialog flow and finally some modules that generate a response and finalize it.
The following example demonstrates different ways to use the execution order of middleware modules and how they can exchange data throughout the request handling.
You can even execute middleware after a request has been ended, e.g. for logging data.