适配器

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:

在某些情况下你可能不想使用socket.io。没问题,Nest允许你使用任何其他的websockets库,使用其他库时,你只需要创建一个适配器就可以了。

我们来以ws作为一个例子。 我们需要创建一个可以实现websocketadapter(@ nestjs /普通)接口的类:

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:

create, bindClientConnectbindMessageHandlers这三种方法是必须的,其他都是可选的。请看如下示例:

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:

最有趣的是bindmessagehandlers功能,在该功能中我们必须将消息和对应的处理程序结合起来。Handler是一个有消息属性( @SubscribeMessage()装饰器中传递)和回调函数(执行函数)的对象。我决定通过type属性识别消息,你可以选择使用其他映射方式。 最后一步--我们必须设置我们的适配器:

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

That's it!

results matching ""

    No results matching ""