Adapters

In some cases you might not want to use socket.io. It's not a problem. Nest allows you to use any other websockets library, you only have to create an adapter.

Let's imagine that you want to use ws.

We have to create a class, which implements WebSocketAdapter (@nestjs/common) interface:

export interface WebSocketAdapter {
    create(port: number);
    createWithNamespace?(port: number, namespace: string);
    bindClientConnect(server, callback: (...args) => void);
    bindClientDisconnect?(client, callback: (...args) => void);
    bindMessageHandlers(client, handlers: MessageMappingProperties[]);
    bindMiddleware?(server, middleware: (socket, next) => void);
}

Three methods are obligatory - create, bindClientConnect and bindMessageHandlers. The rest are optional. Take a look at the example:

import * as WebSocket from 'ws';
import { WebSocketAdapter } from '@nestjs/common';
import { MessageMappingProperties } from '@nestjs/websockets';

class WsAdapter implements WebSocketAdapter {
    public create(port: number) {
        return new WebSocket.Server({ port });
    }
    public bindClientConnect(server, callback: (...args: any[]) => void) {
        server.on('connection', callback);
    }
    public bindMessageHandlers(client, handlers: MessageMappingProperties[]) {
        client.on('message', (buffer) => {
            const data = JSON.parse(buffer);
            const { type } = data;
            const messageHandler = handlers.find((handler) => handler.message === type);
            messageHandler && messageHandler.callback(data);
        });
    }
}

The most interesting is bindMessageHandlers function, where we have to bind messages to appropriate handlers. Handler is an object, with message property (passed in @SubscribeMessage() decorator) and callback (function to execute). I decided to recognize messages by type property, but it's your decision how you want to map them.

The last step - we must set-up our adapter:

const app = NestFactory.create(ApplicationModule);
app.useWebSocketAdapter(new WsAdapter());

That's it!

results matching ""

    No results matching ""