Kest

Search

Search the documentation

Microservices

Pre-request hooks

Run something before every message.

Anything that must happen before the handler is a guard, pipe or interceptor: they all run on message handlers. For work around every message, register an interceptor (or guard or pipe) for the whole service instead of repeating it on each handler:

app.connectMicroservice(TcpOptions(4000)) { useInterceptors(AuditInterceptor::class) }

Typical hooks: authenticate (a guard reading the authorization message header), validate (ValidationPipe), measure, or put a request id from a message header into a RequestContext so logs line up.

@Injectable
class CorrelationInterceptor : Interceptor {
    override suspend fun intercept(ctx: ExecutionContext, next: CallHandler): Any? =
        RequestContext.runSuspending(mapOf("requestId" to (ctx.request.header("x-request-id") ?: UUID.randomUUID().toString()))) { next.handle() }
}

The handler's headers are the message's headers (or gRPC metadata), so a token or a correlation id can ride in a header and be read by the hook exactly as for HTTP.

Read more