Skip to content
Snippets Groups Projects
Commit cbcf068c authored by L4168's avatar L4168
Browse files

added guard for gamestate

parent 1b355c6e
No related branches found
No related tags found
3 merge requests!59Development to master,!36Development,!32Game state
import {
Injectable,
CanActivate,
ExecutionContext,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { GameEntity } from '../game/game.entity';
@Injectable()
export class StatesGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
@InjectRepository(GameEntity)
private gameRepository: Repository<GameEntity>,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
// get game states that are allowed access, identified by @GameStates('state') decorators in controllers
const states = this.reflector.get<string[]>('states', context.getHandler());
console.log(states);
if (!states) {
return true;
}
const request = context.switchToHttp().getRequest();
const gameId = request.params.id;
const gameRef = await this.gameRepository.findOne({
id: gameId,
});
// check that the gameState matches the criteria
if (gameRef && states.includes(gameRef.state)) {
return true;
} else {
throw new HttpException(
`Game is set to ${
gameRef.state
}, operation only valid in states ${states.join(', ')}`,
HttpStatus.BAD_REQUEST,
);
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment