Skip to content
Snippets Groups Projects
Commit 98e131da authored by Samuli Virtapohja's avatar Samuli Virtapohja
Browse files

Merge branch 'gameperson-decorator' into HEAD

parents 21f1604e 8c09e1c0
No related branches found
No related tags found
3 merge requests!59Development to master,!44Development to testing,!40Gameperson decorator
...@@ -22,6 +22,7 @@ import { ...@@ -22,6 +22,7 @@ import {
} from './faction.dto'; } from './faction.dto';
import { FactionService } from './faction.service'; import { FactionService } from './faction.service';
import { Roles, GameStates } from '../shared/guard.decorator'; import { Roles, GameStates } from '../shared/guard.decorator';
import { GamePerson } from 'src/game/gameperson.decorator';
@Controller('faction') @Controller('faction')
export class FactionController { export class FactionController {
...@@ -53,11 +54,11 @@ export class FactionController { ...@@ -53,11 +54,11 @@ export class FactionController {
@Roles('soldier') @Roles('soldier')
@GameStates('CREATED') @GameStates('CREATED')
async joinGroup( async joinGroup(
@User('id') person, @GamePerson() gameperson,
@Param('id') id, @Param('id') gameId,
@Body() data: JoinGameGroupDTO, @Body() data: JoinGameGroupDTO,
) { ) {
return this.factionservice.joinGroup(person, id, data); return this.factionservice.joinGroup(gameperson, data);
} }
@UseInterceptors(ClassSerializerInterceptor) @UseInterceptors(ClassSerializerInterceptor)
......
...@@ -110,13 +110,9 @@ export class FactionService { ...@@ -110,13 +110,9 @@ export class FactionService {
}); });
} }
async joinGroup(person, gameId, data: JoinGameGroupDTO) { async joinGroup(gameperson, data: JoinGameGroupDTO) {
const gamePerson = await this.game_PersonRepository.findOne({ gameperson.group = data.groupId;
person: person, await this.game_PersonRepository.save(gameperson);
game: gameId,
});
gamePerson.group = data.groupId;
await this.game_PersonRepository.save(gamePerson);
return { return {
message: 'Joined group', message: 'Joined group',
}; };
......
...@@ -171,25 +171,25 @@ export class GameService { ...@@ -171,25 +171,25 @@ export class GameService {
// returns name and id of each game // returns name and id of each game
async listGames(state) { async listGames(state) {
if(state == null){ if (state == null) {
const games = await this.gameRepository.find(); const games = await this.gameRepository.find();
return games.map(game => { return games.map(game => {
return game.gameObject(); return game.gameObject();
}); });
} } else if (state == 'ONGOING') {
else if(state == 'ONGOING'){
const games = await this.gameRepository.find({ const games = await this.gameRepository.find({
where: [ where: [
{state: 'CREATED'}, {state: 'STARTED'}, {state: 'PAUSED'}, { state: 'CREATED' },
] { state: 'STARTED' },
{ state: 'PAUSED' },
],
}); });
return games.map(game => { return games.map(game => {
return game.gameObject(); return game.gameObject();
}); });
} } else {
else{
const games = await this.gameRepository.find({ const games = await this.gameRepository.find({
where: {state: state} where: { state: state },
}); });
return games.map(game => { return games.map(game => {
return game.gameObject(); return game.gameObject();
......
import { createParamDecorator } from '@nestjs/common';
/*
gives service access to the gameperson object
Game_PersonEntity {
gamepersonId
role
faction
}
*/
export const GamePerson = createParamDecorator((data, req) => {
return data ? req.gameperson[data] : req.gameperson;
});
...@@ -27,7 +27,7 @@ export class ScoreController { ...@@ -27,7 +27,7 @@ export class ScoreController {
return this.scoreService.scoreTick(gameId); return this.scoreService.scoreTick(gameId);
} }
// shows scores, :id is gameId // shows scores, :id is gameId
@Get('get-score/:id') @Get('get-score/:id')
@GameStates('STARTED') @GameStates('STARTED')
async getScores(@Param('id') gameId: GameEntity) { async getScores(@Param('id') gameId: GameEntity) {
......
...@@ -89,26 +89,25 @@ export class ScoreService { ...@@ -89,26 +89,25 @@ export class ScoreService {
async getScores(gameId: GameEntity) { async getScores(gameId: GameEntity) {
// find games factions // find games factions
const factions = await this.factionRepository.find({ const factions = await this.factionRepository.find({
where: {game: gameId,}, where: { game: gameId },
relations: ['game'], relations: ['game'],
}); });
let scores = []; let scores = [];
await Promise.all( await Promise.all(
factions.map(async factionNow => { factions.map(async factionNow => {
let score = await this.scoreRepository.findOne({ let score = await this.scoreRepository.findOne({
where: {faction: factionNow}, where: { faction: factionNow },
relations: ['faction'], relations: ['faction'],
order: {scoreTimeStamp: 'DESC'}, order: { scoreTimeStamp: 'DESC' },
}); });
//if score was found, put info to scores array //if score was found, put info to scores array
if (score.faction) { if (score.faction) {
let index = await scores.findIndex( let index = await scores.findIndex(i => i.faction === score.faction);
i => i.faction === score.faction,
);
scores.push(score); scores.push(score);
} }
})) }),
return scores; );
return scores;
} }
} // } //
......
...@@ -34,9 +34,12 @@ export class RolesGuard implements CanActivate { ...@@ -34,9 +34,12 @@ export class RolesGuard implements CanActivate {
const gameId = request.params.id; const gameId = request.params.id;
request.user = await this.getUserObject(request.headers.authorization); request.user = await this.getUserObject(request.headers.authorization);
const role = await this.game_PersonRepository.findOne({ const role = await this.game_PersonRepository.findOne({
person: request.user['id'], where: { person: request.user['id'], game: gameId },
game: gameId, relations: ['faction'],
}); });
// add gameperson role to the request
// @GamePerson decorator can access it and pass it to service
request.gameperson = role;
// check that the role matches the criteria and that token is valid for this game // check that the role matches the criteria and that token is valid for this game
return role && roles.includes(role['role']); return role && roles.includes(role['role']);
} }
......
...@@ -12,7 +12,7 @@ import { TaskService } from './task.service'; ...@@ -12,7 +12,7 @@ import { TaskService } from './task.service';
import { CreateTaskDTO, EditTaskDTO, DeleteTaskDTO } from './task.dto'; import { CreateTaskDTO, EditTaskDTO, DeleteTaskDTO } from './task.dto';
import { Roles } from '../shared/guard.decorator'; import { Roles } from '../shared/guard.decorator';
import { ValidationPipe } from '../shared/validation.pipe'; import { ValidationPipe } from '../shared/validation.pipe';
import { User } from '../user/user.decorator'; import { GamePerson } from 'src/game/gameperson.decorator';
@Controller('task') @Controller('task')
export class TaskController { export class TaskController {
...@@ -49,7 +49,7 @@ export class TaskController { ...@@ -49,7 +49,7 @@ export class TaskController {
// :id is the id of the game // :id is the id of the game
@Get('get-tasks/:id') @Get('get-tasks/:id')
@Roles('soldier', 'factionleader', 'admin') @Roles('soldier', 'factionleader', 'admin')
async fetchTasks(@User('id') person, @Param('id') id: string) { async fetchTasks(@GamePerson() gameperson, @Param('id') id: string) {
return this.taskService.fetchTasks(person, id); return this.taskService.fetchTasks(gameperson, id);
} }
} }
...@@ -5,12 +5,11 @@ import { TaskService } from './task.service'; ...@@ -5,12 +5,11 @@ import { TaskService } from './task.service';
import { TaskController } from './task.controller'; import { TaskController } from './task.controller';
import { TaskEntity } from './task.entity'; import { TaskEntity } from './task.entity';
import { FactionEntity } from '../faction/faction.entity'; import { FactionEntity } from '../faction/faction.entity';
import { Game_PersonEntity } from '../game/game.entity';
import { NotificationModule } from '../notifications/notifications.module'; import { NotificationModule } from '../notifications/notifications.module';
@Module({ @Module({
imports: [ imports: [
TypeOrmModule.forFeature([TaskEntity, FactionEntity, Game_PersonEntity]), TypeOrmModule.forFeature([TaskEntity, FactionEntity]),
NotificationModule, NotificationModule,
], ],
controllers: [TaskController], controllers: [TaskController],
......
...@@ -15,8 +15,6 @@ export class TaskService { ...@@ -15,8 +15,6 @@ export class TaskService {
private taskRepository: Repository<TaskEntity>, private taskRepository: Repository<TaskEntity>,
@InjectRepository(FactionEntity) @InjectRepository(FactionEntity)
private factionRepository: Repository<FactionEntity>, private factionRepository: Repository<FactionEntity>,
@InjectRepository(Game_PersonEntity)
private gamePersonRepository: Repository<Game_PersonEntity>,
private notificationGateway: NotificationGateway, private notificationGateway: NotificationGateway,
) {} ) {}
...@@ -78,15 +76,8 @@ export class TaskService { ...@@ -78,15 +76,8 @@ export class TaskService {
throw new HttpException('Task not found', HttpStatus.BAD_REQUEST); throw new HttpException('Task not found', HttpStatus.BAD_REQUEST);
} }
async fetchTasks(user, taskGame) { async fetchTasks(gameperson, taskGame) {
const gamePerson = await this.gamePersonRepository.findOne({ if (gameperson.role == 'admin') {
where: {
person: user,
game: taskGame,
},
relations: ['faction'],
});
if (gamePerson.role == 'admin') {
return await this.taskRepository.find({ return await this.taskRepository.find({
where: { taskGame: taskGame }, where: { taskGame: taskGame },
relations: ['faction', 'taskWinner'], relations: ['faction', 'taskWinner'],
...@@ -97,7 +88,7 @@ export class TaskService { ...@@ -97,7 +88,7 @@ export class TaskService {
where: [ where: [
{ {
taskGame: taskGame, taskGame: taskGame,
faction: gamePerson.faction.factionId, faction: gameperson.faction.factionId,
}, },
{ {
taskGame: taskGame, taskGame: taskGame,
......
import { import { Controller, Post, Param, UsePipes, Body, Get } from '@nestjs/common';
Controller,
Post,
Param,
UseGuards,
UsePipes,
Body,
Get,
} from '@nestjs/common';
import { TrackingService } from './tracking.service'; import { TrackingService } from './tracking.service';
import { TrackingDTO } from './tracking.dto';
import { User } from '../user/user.decorator'; import { User } from '../user/user.decorator';
import { Roles, GameStates } from '../shared/guard.decorator'; import { Roles, GameStates } from '../shared/guard.decorator';
import { ValidationPipe } from '../shared/validation.pipe'; import { ValidationPipe } from '../shared/validation.pipe';
import { GeoDTO } from './geo.dto'; import { GeoDTO } from './geo.dto';
import { GamePerson } from 'src/game/gameperson.decorator';
@Controller('tracking') @Controller('tracking')
export class TrackingController { export class TrackingController {
...@@ -26,17 +18,17 @@ export class TrackingController { ...@@ -26,17 +18,17 @@ export class TrackingController {
@GameStates('STARTED') @GameStates('STARTED')
@UsePipes(new ValidationPipe()) @UsePipes(new ValidationPipe())
async trackLocation( async trackLocation(
@User('id') userId, @GamePerson() gameperson,
@Param('id') id, @Param('id') id,
@Body() trackdata: GeoDTO, @Body() trackdata: GeoDTO,
) { ) {
return this.trackingservice.trackLocation(userId, id, trackdata); return this.trackingservice.trackLocation(gameperson, id, trackdata);
} }
@Get('players/:id') @Get('players/:id')
@Roles('admin', 'factionleader') @Roles('admin', 'factionleader')
@GameStates('STARTED', 'PAUSED') @GameStates('STARTED', 'PAUSED')
async getPlayerLocations(@User('id') userId, @Param('id') gameId) { async getPlayerLocations(@GamePerson() gameperson, @Param('id') gameId) {
return this.trackingservice.getPlayers(userId, gameId); return this.trackingservice.getPlayers(gameperson, gameId);
} }
} }
...@@ -4,10 +4,9 @@ import { TypeOrmModule } from '@nestjs/typeorm'; ...@@ -4,10 +4,9 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { TrackingController } from './tracking.controller'; import { TrackingController } from './tracking.controller';
import { TrackingService } from './tracking.service'; import { TrackingService } from './tracking.service';
import { TrackingEntity } from './tracking.entity'; import { TrackingEntity } from './tracking.entity';
import { Game_PersonEntity } from '../game/game.entity';
@Module({ @Module({
imports: [TypeOrmModule.forFeature([TrackingEntity, Game_PersonEntity])], imports: [TypeOrmModule.forFeature([TrackingEntity])],
controllers: [TrackingController], controllers: [TrackingController],
providers: [TrackingService], providers: [TrackingService],
}) })
......
import { Injectable, HttpStatus, HttpException } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm'; import { Repository } from 'typeorm';
import { Game_PersonEntity } from '../game/game.entity'; import { Game_PersonEntity } from '../game/game.entity';
import { TrackingEntity } from './tracking.entity'; import { TrackingEntity } from './tracking.entity';
import { TrackingDTO } from './tracking.dto';
import { FactionEntity } from '../faction/faction.entity';
import { NotificationGateway } from 'src/notifications/notifications.gateway';
import { GeoDTO } from './geo.dto'; import { GeoDTO } from './geo.dto';
@Injectable() @Injectable()
...@@ -14,26 +11,17 @@ export class TrackingService { ...@@ -14,26 +11,17 @@ export class TrackingService {
constructor( constructor(
@InjectRepository(TrackingEntity) @InjectRepository(TrackingEntity)
private trackingrepository: Repository<TrackingEntity>, private trackingrepository: Repository<TrackingEntity>,
@InjectRepository(Game_PersonEntity)
private gamepersonrepository: Repository<Game_PersonEntity>,
) {} ) {}
async trackLocation(personId, gameId, trackdata: GeoDTO) { async trackLocation(
// find player gameperson: Game_PersonEntity,
let gameperson = await this.gamepersonrepository.findOne({ gameId,
where: { game: gameId, person: personId }, trackdata: GeoDTO,
relations: ['faction'], ) {
}); // find ref to gameperson's tracking data
if (!gameperson) {
throw new HttpException(
'You have not joined this game',
HttpStatus.BAD_REQUEST,
);
}
let trackedperson = await this.trackingrepository.findOne({ let trackedperson = await this.trackingrepository.findOne({
gamepersonId: gameperson, gamepersonId: gameperson,
}); });
// if player has pushed tracking data, update entry // if player has pushed tracking data, update entry
if (trackedperson) { if (trackedperson) {
trackdata['time'] = Date.now(); trackdata['time'] = Date.now();
...@@ -41,7 +29,7 @@ export class TrackingService { ...@@ -41,7 +29,7 @@ export class TrackingService {
trackedperson.data.push(trackdata); trackedperson.data.push(trackdata);
//add timestamp //add timestamp
await this.trackingrepository.save(trackedperson); await this.trackingrepository.save(trackedperson);
return { code: 201, message: 'Location updated!' }; return { message: 'Location updated!' };
} else { } else {
// first entry will be empty // first entry will be empty
trackdata['time'] = Date.now(); trackdata['time'] = Date.now();
...@@ -53,18 +41,12 @@ export class TrackingService { ...@@ -53,18 +41,12 @@ export class TrackingService {
trackedperson.gamepersonId = gameperson; trackedperson.gamepersonId = gameperson;
await this.trackingrepository.save(trackedperson); await this.trackingrepository.save(trackedperson);
return { code: 201, message: 'Entry Created!' }; return { message: 'Entry Created!' };
} }
} }
// get player data while game is running // get player data while game is running
async getPlayers(userId, gameId) { async getPlayers(gameperson, gameId) {
// get gameperson
const gameperson = await this.gamepersonrepository.findOne({
where: { person: userId, game: gameId },
relations: ['faction'],
});
let playerdata; let playerdata;
// get playerdata // get playerdata
if (gameperson.faction) { if (gameperson.faction) {
...@@ -93,10 +75,4 @@ export class TrackingService { ...@@ -93,10 +75,4 @@ export class TrackingService {
return currentdata; return currentdata;
} }
private async mapFunction(data): Promise<Number> {
return await data.map(type => {
return type;
});
}
} }
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