@betsys-nestjs/websocket
v2.0.0
Published
Library for handling websocket connections
Downloads
4
Maintainers
Keywords
Readme
Websocket library
A base for handling websocket connections including implementation of RedisAdapter using Redis library and Monitoring using Monitoring library
Dependencies
| Package | Version | | --------------------------- | --------------- | | @nestjs/platform-socket.io | ^10.0.0 | | @nestjs/websockets | ^10.0.0 | | socket.io | ^4.5.4 | | ws | ^8.11.0 | | @nestjs/common | ^10.0.0 | | @nestjs/core | ^10.0.0 | | @betsys-nestjs/monitoring | ^6.0.0 | | @betsys-nestjs/logger | ^4.0.1 | | @betsys-nestjs/config-utils | ^1.0.3 | | @nestjs/terminus | ^10.0.0 | | reflect-metadata | >=0.1.13 <0.2.0 | | rxjs | >=7.8.0 <8.0.0 |
Usage
To start using this library simply import WebsocketModule
and use it like this:
import { WebsocketModule } from '@betsys-nestjs/websocket'
import { Module } from "@nestjs/common";
@Module({
imports: [
WebsocketModule.forRoot()
]
})
class AppModule {
}
Then you can start using the module exports.
AbstractGateway
and WebsocketMonitoringService
usage example:
import {
ConnectedSocket,
WebSocketGateway,
AbstractGateway,
WebsocketMonitoringService
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
@WebSocketGateway({
transports: ['websocket'],
namespace: 'test',
})
export class TestSocketGateway extends AbstractGateway {
constructor(
private readonly monitoring: WebsocketMonitoringService,
) {
super(monitoring);
}
afterInit(server: Server): void {
super.afterInit(server);
}
async handleConnection(@ConnectedSocket() socket: Socket): Promise<void> {
try {
await super.handleConnection(socket);
} catch (e) {
socket.disconnect(true);
}
}
async handleDisconnect(@ConnectedSocket() socket: Socket): Promise<void> {
try {
super.handleDisconnect(socket);
} finally {
socket.leave('');
}
}
}
RedisAdapter
usage example:
import { RedisIoAdapter } from '@betsys/websocket';
app.useWebSocketAdapter(new RedisIoAdapter(app, redisConfig));
- Simply add this line to application bootstrap() method.