53 lines
1.7 KiB
TypeScript
53 lines
1.7 KiB
TypeScript
import { Injectable, Logger, UseFilters } from '@nestjs/common';
|
|
import {
|
|
ConnectedSocket,
|
|
OnGatewayConnection,
|
|
MessageBody,
|
|
SubscribeMessage,
|
|
WebSocketGateway,
|
|
} from '@nestjs/websockets';
|
|
import { PlayerService } from './players/player.service';
|
|
import { GameService } from 'src/games/game.service';
|
|
import { Socket } from 'socket.io';
|
|
import { ClientEvent, CreateLobbyEvent, JoinLobbyEvent } from 'interface';
|
|
import { WsExceptionFilter } from './websocket-exception-filter';
|
|
import { PlayerNotFoundException } from './exceptions';
|
|
|
|
@WebSocketGateway({ cors: true })
|
|
@Injectable()
|
|
export class AppService implements OnGatewayConnection {
|
|
private readonly logger = new Logger(AppService.name);
|
|
|
|
constructor(
|
|
private readonly playerService: PlayerService,
|
|
private readonly gameService: GameService,
|
|
) {}
|
|
handleConnection(client: Socket) {
|
|
this.playerService.createPlayer(client.id);
|
|
}
|
|
|
|
@UseFilters(new WsExceptionFilter([PlayerNotFoundException]))
|
|
@SubscribeMessage(ClientEvent.CREATE_LOBBY)
|
|
handleCreateLobby(
|
|
@ConnectedSocket() client: Socket,
|
|
@MessageBody() event: CreateLobbyEvent,
|
|
) {
|
|
this.playerService.addUserName(client.id, event.userName);
|
|
this.gameService.createLobby(this.playerService.getPlayer(client.id));
|
|
this.logger.log('Se ha creado un lobby');
|
|
}
|
|
|
|
@SubscribeMessage(ClientEvent.JOIN_LOBBY)
|
|
handleJoinLobby(
|
|
@ConnectedSocket() client: Socket,
|
|
@MessageBody() event: JoinLobbyEvent,
|
|
) {
|
|
this.playerService.addUserName(client.id, event.userName);
|
|
this.gameService.joinGame(
|
|
this.playerService.getPlayer(client.id),
|
|
event.lobbyId,
|
|
);
|
|
this.logger.log('Te has unido a un lobby');
|
|
}
|
|
}
|