Middlewares can be registered
- either globally, with
app.usefor all incoming requests,
- or at method level with
addService, where instead of a single handler, an array of handlers can be provided (handler and middleware have the same API).
Note that grpc does not provide API to intercept all incoming requests, it only provides handlers to specific RPCs. That is why even global ProtoCat's middlewares do not handle requests that request unimplemented gRPC service for example.
Here is an example of a simple logger middleware. Apart from
call, each middleware (handler alike) receives a
next function. This is a callstack of all subsequent middlewares and handlers. This feature is demonstrated in a simple logger middleware below.
Unless you want to stop execution of the subsequent middlewares, you must call
next. Not awaiting (or returning) it will probably result in unexpected behavior, especially in calls without server-streaming.
All middlewares are executed in the order they were registered, followed by an execution of handlers in provided order, regardless of middleware-service order. Note that in the following example,
C middleware is registered after
CatService and it is still called, even before the handlers.