WebSockets
Interceptors
Wrap message handlers: time them, log them, change their results.
An interceptor wraps a handler call, and it works for message handlers too: it runs before the handler, calls next.handle(), and sees the value the handler returns (which becomes the acknowledgement sent back to the client).
@Injectable
class MessageTiming : Interceptor {
private val log = Logger("WsTiming")
override suspend fun intercept(ctx: ExecutionContext, next: CallHandler): Any? {
val t = System.nanoTime()
try { return next.handle() }
finally { log.debug("${ctx.handler} took ${(System.nanoTime() - t) / 1_000_000} ms") }
}
}
@WebSocketGateway("/chat") @UseInterceptors(MessageTiming::class)
class ChatGateway { ... }Typical uses: metrics per event (count messages, time handlers; see Metrics), auditing who sent what, rate limiting a chatty client, or adding a field to every acknowledgement.
For flood control, count messages per ctx.request / connection inside an interceptor and throw TooManyRequestsException-style errors (an HttpException with status 429) when a client sends too many: the sender receives an exception message and other clients are unaffected.
The interceptor sees the handshake as the request, the handler name, and the annotations on the handler and gateway, like for HTTP. Attach to a gateway or a single handler with @UseInterceptors.