How to use @nestjs/websockets - 10 common examples

To help you get started, weโ€™ve selected a few @nestjs/websockets examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github danielwii / asuna-node-server / src / modules / ws / ws.gateway.ts View on Github external
const logger = LoggerFactory.getLogger('WSGateway');

@WebSocketGateway(3002, {
  path: '/',
  // pingInterval: 30000, // default 25e3
  // pingTimeout: 4000, // default 5e3
  serveClient: false,
})
export class WSGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  private server: Server;

  private readonly timestamp = Date.now();

  @SubscribeMessage('events')
  onHeartbeat(client: any, data: any): WsResponse {
    console.log(data);
    const event = 'events';
    const response = `events-${pkg.version}-${this.timestamp}`;
    return { event, data: response };
  }

  @SubscribeMessage('events2')
  onEvents2(client: any, data: any): WsResponse {
    console.log(data);
    const event = 'events';
    const response = `events-${pkg.version}-${this.timestamp}`;
    return { event, data: response };
  }

  public afterInit(server: any): any {
github jimmyleray / Emendare / server-nest / src / gateways / text.gateway.ts View on Github external
import {
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer
} from '@nestjs/websockets'
import { Socket, Server } from 'socket.io'
// Service
import { TextService } from '../services'

@WebSocketGateway()
export class TextGateway {
  constructor(private textService: TextService) {}
  @WebSocketServer()
  io: Server

  @SubscribeMessage('text')
  async handleText(client: Socket, data: { data: { id: string } }) {
    try {
      const response = await this.textService.getText(data.data.id)
      client.emit('text/' + data.data.id, response)
    } catch (error) {
      console.error(error)
    }
  }

  @SubscribeMessage('texts')
github jimmyleray / Emendare / server-nest / src / gateways / amend.gateway.ts View on Github external
client: Socket,
    data: { token: string; data: { id: string } }
  ) {
    try {
      const response = await this.amendService.downVoteAmend(
        data.data.id,
        data.token,
        this.io
      )
      client.emit('downVoteAmend', response)
    } catch (error) {
      console.error(error)
    }
  }

  @SubscribeMessage('indVoteAmend')
  async handleIndVoteAmend(
    client: Socket,
    data: { token: string; data: { id: string } }
  ) {
    try {
      const response = await this.amendService.upVoteAmend(
        data.data.id,
        data.token,
        this.io
      )
      client.emit('indVoteAmend', response)
    } catch (error) {
      console.error(error)
    }
  }
github anton-g / quizify / server / src / game / gateways / host.gateway.ts View on Github external
}

  @UseGuards(EventAuthGuard)
  @UsePipes(SocketAuthPipe)
  @SubscribeMessage(GameEvents.ChangePlaylist)
  async onChangePlaylist(client: Socket, { data, user }) {
    const game = await this.gameService.setPlaylist(user, data.playlist, data.lang)

    this.server.to(game.key).emit(GameEvents.ChangePlaylist, new PlayerGameInfoDto(game))

    return new GameDto(game)
  }

  @UseGuards(EventAuthGuard)
  @UsePipes(SocketAuthPipe)
  @SubscribeMessage(GameEvents.Start)
  async onStart(client: Socket, { data, user }) {
    const key = data.key
    let game = await this.gameService.get(key)
    game = await this.gameService.setState(game.key, GameState.Paused)

    await this.spotify.pausePlayback(user)

    const gameUpdate: Partial = {
      state: game.state
    }
    this.server.to(data.key).emit(GameEvents.Start, gameUpdate)

    console.log(`[${key}] Start game`)
    return new GameDto(game)
  }
github anton-g / quizify / server / src / game / gateways / player.gateway.ts View on Github external
@SubscribeMessage(GameEvents.Join)
  async onJoin(client: Socket, userId) {
    const game = await this.playerService.connect(userId, client.id)
    client.join(game.key)

    const gameUpdate: Partial = {
      players: game.players
    }
    this.server.to(game.key).emit(GameEvents.Update, gameUpdate)

    console.log(`[${game.key}] User ${userId} joined`)
    return new PlayerGameInfoDto(game)
  }

  @SubscribeMessage(GameEvents.Buzz)
  async onBuzz(client: Socket, userId) {
    const game: Game = await this.gameService.getByPlayerId(userId)
    if (game.state !== GameState.Playing) return

    this.server.to(game.key).emit(GameEvents.Pause)
    this.gameService.setState(game.key, GameState.Paused)
    this.server.to(game.host.socket).emit(GameEvents.Buzzed, userId)

    this.spotify.pausePlayback(game.host.user)

    console.log(`[${game.key}] User ${userId} buzzed`)
  }

  @SubscribeMessage(GameEvents.Leave)
  async onLeave(client: Socket) {
    const game = await this.playerService.leave(client.id)
github meepobrother / meepo-hunli / service / src / app.controller.ts View on Github external
@WebSocketGateway({ port: 1314 })
export class AppGeteway {
  @WebSocketServer() server;

  constructor(private hunli: HunliDiscussService, private fuyue: HunliFuyueService) {

  }

  @SubscribeMessage('hunli.discuss')
  async handelHunliDiscuss(sender, data) {
    const list = await this.hunli.findAll();
    sender.emit('hunli.discuss', list);
  }

  @SubscribeMessage('hunli.discuss.add')
  async handelHunliDiscussAdd(sender, data) {
    const item = await this.hunli.addOne(data);
    const list = await this.hunli.findAll();
    sender.broadcast.emit('hunli.discuss.add', data);
    sender.emit('hunli.discuss.add', data);
  }

  @SubscribeMessage('hunli.fuyue')
  async handelHunliFuyue(sender, data) {
    const list = await this.fuyue.findAll();
    sender.emit('hunli.fuyue', list);
  }

  @SubscribeMessage('hunli.fuyue.add')
  async handelHunliFuyueAdd(sender, data) {
    const item = await this.fuyue.addOne(data);
github jimmyleray / Emendare / server / src / gateways / amend.gateway.ts View on Github external
import { withTryCatch, withAuthentication, withResponse } from '../common'
import { IMessage } from '../../../interfaces'

@WebSocketGateway()
export class AmendGateway {
  constructor(
    @Inject('AuthService')
    private readonly authService: AuthService,
    @Inject('AmendService')
    private readonly amendService: AmendService
  ) {}

  @WebSocketServer()
  io: Server

  @SubscribeMessage('amend')
  @withTryCatch
  async handleAmend(client: Socket, message: IMessage<{ id: string }>) {
    const response = await this.amendService.getAmend(message.data.id)
    client.emit('amend/' + message.data.id, response)
  }

  @SubscribeMessage('postAmend')
  @withResponse('postAmend')
  @withTryCatch
  @withAuthentication
  async handlePostAmend(
    client: Socket,
    message: IMessage<{
      name: string
      description: string
      patch: string
github meepobrother / meepo-hunli / service / src / app.controller.ts View on Github external
@SubscribeMessage('hunli.discuss')
  async handelHunliDiscuss(sender, data) {
    const list = await this.hunli.findAll();
    sender.emit('hunli.discuss', list);
  }

  @SubscribeMessage('hunli.discuss.add')
  async handelHunliDiscussAdd(sender, data) {
    const item = await this.hunli.addOne(data);
    const list = await this.hunli.findAll();
    sender.broadcast.emit('hunli.discuss.add', data);
    sender.emit('hunli.discuss.add', data);
  }

  @SubscribeMessage('hunli.fuyue')
  async handelHunliFuyue(sender, data) {
    const list = await this.fuyue.findAll();
    sender.emit('hunli.fuyue', list);
  }

  @SubscribeMessage('hunli.fuyue.add')
  async handelHunliFuyueAdd(sender, data) {
    const item = await this.fuyue.addOne(data);
    if (item) {
      const list = await this.fuyue.findAll();
      sender.broadcast.emit('hunli.fuyue.add', data);
      sender.emit('hunli.fuyue.add', data);
    }
  }
}
github fischermatte / geolud / geolud-server-node / src / chat / chat.gateway.ts View on Github external
private subject: ReplaySubject = new ReplaySubject(10, 1000 * 60 * 2);
  private lastChatNotificationEmail: Date;

  constructor(@Inject('MailService') private mailService: MailService) {}

  afterInit(server: Server): void {
    this.server = server;
    this.subject.subscribe(message => {
      this.server.clients.forEach(client => {
        client.send(JSON.stringify({ event: 'chat', data: message }));
      });
    });
  }

  @SubscribeMessage('chat')
  onMessage(client, message: ChatMessage): void {
    message.timestamp = new Date();
    this.notifyChatAction(message);
    this.subject.next(message);
  }

  private notifyChatAction(message: ChatMessage): void {
    const msg: string = JSON.stringify(message);
    Logger.log('chat action going on: ' + msg);
    const oneHourEarlier: Date = new Date();
    oneHourEarlier.setTime(oneHourEarlier.getTime() - 60 * 60 * 1000);
    if (this.lastChatNotificationEmail == null || this.lastChatNotificationEmail < oneHourEarlier) {
      this.mailService.sendEmail(null, null, 'GEOLUD-SITE: Chat actions going on ...', msg);
    }
    this.lastChatNotificationEmail = new Date();
  }
github kelvin-mai / nest-ideas-api / src / app.gateway.ts View on Github external
import { Logger } from '@nestjs/common';
import {
  WebSocketGateway,
  WebSocketServer,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from '@nestjs/websockets';

@WebSocketGateway(4001, { transport: ['websocket'] })
export class AppGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  wss;

  private logger = new Logger('AppGateway');

  handleConnection(client) {
    this.logger.log('New client connected');
    client.emit('connection', 'Successfully connected to server');
  }

  handleDisconnect(client) {
    this.logger.log('Client disconnected');
  }
}

@nestjs/websockets

Nest - modern, fast, powerful node.js web framework (@websockets)

MIT
Latest version published 18 hours ago

Package Health Score

94 / 100
Full package analysis

Similar packages