docs-nestjs-com-websockets-adapter...
docs-nestjs-com-websockets-adapter...
Adapters
The WebSockets module is platform-agnostic, hence, you can bring your
own library (or even a native implementation) by making use of
WebSocketAdapter interface. This interface forces to implement few
Build your website for
methods described in the following table: just $3.88/mth. More
value and performance
with Namecheap.
ADS VIA CARBON
create
bindClientConnect
bindClientDisconnect
bindMessageHandlers
close
Terminates a server instance
Extend socket.io
The socket.io package is wrapped in an IoAdapter class. What if you would like to enhance the basic
functionality of the adapter? For instance, your technical requirements require a capability to
broadcast events across multiple load-balanced instances of your web service. For this, you can
extend IoAdapter and override a single method which responsibility is to instantiate new socket.io
servers. But first of all, let's install the required package.
WARNING
To use socket.io with multiple load-balanced instances you either have to disable polling by
setting transports: ['websocket'] in your clients socket.io configuration or you have to
enable cookie based routing in your load balancer. Redis alone is not enough. See here for more
information.
app.useWebSocketAdapter(redisIoAdapter);
Ws library
Another available adapter is a WsAdapter which in turn acts like a proxy between the framework and
integrate blazing fast and thoroughly tested ws library. This adapter is fully compatible with native
browser WebSockets and is far faster than socket.io package. Unluckily, it has significantly fewer
functionalities available out-of-the-box. In some cases, you don't necessarily need them though.
HINT
ws library does not support namespaces (communication channels popularised by
socket.io ). However, to somehow mimic this feature, you can mount multiple ws servers on
different paths (example: @WebSocketGateway({ path: '/users' }) ).
HINT
The WsAdapter is imported from @nestjs/platform-ws .
The wsAdapter is designed to handle messages in the { event: string, data: any } format. If
you need to receive and process messages in a different format, you'll need to configure a message
parser to convert them into this required format.
Alternatively, you can configure the message parser after the adapter is created by using the
setMessageParser method.
ws-adapter.ts JS
bindMessageHandlers(
client: WebSocket,
handlers: MessageMappingProperties[],
process: (data: any) => Observable<any>,
) {
fromEvent(client, 'message')
.pipe(
mergeMap(data => this.bindMessageHandler(data, handlers, process)),
filter(result => result),
)
.subscribe(response => client.send(JSON.stringify(response)));
}
bindMessageHandler(
buffer,
handlers: MessageMappingProperties[],
process: (data: any) => Observable<any>,
): Observable<any> {
const message = JSON.parse(buffer.data);
const messageHandler = handlers.find(
handler => handler.message === message.event,
);
if (!messageHandler) {
return EMPTY;
}
return process(messageHandler.callback(message.data));
}
close(server) {
server.close();
}
}
HINT
When you want to take advantage of ws library, use built-in WsAdapter instead of creating your
own one.
main.ts JS
Example
A working example that uses WsAdapter is available here.
Support us
Nest is an MIT-licensed open source project. It can grow thanks to the support by these awesome
people. If you'd like to join them, please read more here.
Principal Sponsors
Sponsors / Partners
Become a sponsor
Email address..