39 lines
1.1 KiB
TypeScript
39 lines
1.1 KiB
TypeScript
import { Injectable, Logger } from '@nestjs/common';
|
|
import { Player } from './player';
|
|
import {
|
|
InvalidPlayerNameException,
|
|
MissingPlayerNameException,
|
|
PlayerNotFoundException,
|
|
} from 'src/exceptions';
|
|
import { Socket } from 'socket.io/dist/socket';
|
|
|
|
@Injectable()
|
|
export class PlayerService {
|
|
private readonly logger = new Logger(PlayerService.name);
|
|
private readonly players: Map<string, Player> = new Map();
|
|
private readonly userNameValidator: RegExp = /^[a-zA-Z\s]{1,20}$/;
|
|
|
|
createPlayer(socket: Socket) {
|
|
const player: Player = new Player(socket);
|
|
this.players.set(player.socketId, player);
|
|
}
|
|
|
|
addUserName(socketId: string, userName: string) {
|
|
if (!userName) {
|
|
throw new MissingPlayerNameException();
|
|
}
|
|
if (!this.userNameValidator.test(userName)) {
|
|
throw new InvalidPlayerNameException(userName);
|
|
}
|
|
this.players.get(socketId).userName = userName;
|
|
}
|
|
|
|
getPlayer(socketId: string): Player {
|
|
const player = this.players.get(socketId);
|
|
if (!player) {
|
|
throw new PlayerNotFoundException(socketId);
|
|
}
|
|
return player;
|
|
}
|
|
}
|