Gateways

There are special components in Nest called Gateways. Gateways help us to create real-time web apps. They are some kind of encapsulated socket.io features adjusted to framework architecture.

import { WebSocketGateway } from '@nestjs/websockets';

@WebSocketGateway()
export class UsersGateway {}

By default - server runs on port 80 and with default namespace. We can easily change those settings:

@WebSocketGateway({ port: 81, namespace: 'users' })

Of course - server will run only if UsersGateway is listed in module components array, so we have place it there:

@Module({
    controllers: [ UsersController ],
    components: [ UsersService, UsersGateway ],
    exports: [ UsersService ],
})

There are three useful events of Gateway:

  • afterInit, which gets as an argument native server socket.io object,
  • handleConnection and handleDisconnect, which gets as an argument native client socket.io object.

There are special interfaces, which helps to manage lifecycle hooks:

  • OnGatewayInit
  • OnGatewayConnection
  • OnGatewayDisconnect

What with messages?

In Gateway, we can simply subscribe to emitted messages:

import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets';

@WebSocketGateway({ port: 81, namespace: 'users' })
export class UsersGateway {
    @SubscribeMessage('drop')
    handleDropMessage(sender, data) {
        // sender is a native socket.io client object
    }
}

And from client side:

import * as io from 'socket.io-client';
const socket = io('http://URL:PORT/');
socket.emit('drop', { msg: 'test' });

@WebSocketServer()

If you want to assign to chosen property socket.io native server instance, you could simply decorate it with @WebSocketServer() decorator.

import { WebSocketGateway, WebSocketServer, SubscribeMessage } from '@nestjs/websockets';

@WebSocketGateway({ port: 81, namespace: 'users' })
export class UsersGateway {
    @WebSocketServer() 
    private server: object;

    @SubscribeMessage('drop')
    handleDropMessage(sender, data) {
        // sender is a native socket.io client object
    }
}

Value will be assigned after server initialization.

Dependency injection

Gateway is a Component, so it can inject dependencies through constructor. Gateway also can be injected into another component.

results matching ""

    No results matching ""