Skip to content

Commit

Permalink
refactor!: update Game model to use team names (tf2pickup-org#434)
Browse files Browse the repository at this point in the history
* update Game model to use team names
* refactor pickTeams()
* add migration

Use 'blu' and 'red' to identify teams in the GameModel. Makes the 'teams' field obsolete.

BREAKING CHANGE: Game.teams is now gone, GamePlayer.teamId is moved to GamePlayer.team
  • Loading branch information
garrappachc authored Jun 13, 2020
1 parent 8448a0a commit 3fae9ca
Show file tree
Hide file tree
Showing 22 changed files with 616 additions and 407 deletions.
9 changes: 9 additions & 0 deletions .migrate
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"lastRun": "1592050029364-use-tf2-team-names.js",
"migrations": [
{
"title": "1592050029364-use-tf2-team-names.js",
"timestamp": 1592050148283
}
]
}
37 changes: 37 additions & 0 deletions migrations/1592050029364-use-tf2-team-names.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict'

const mongodb = require('mongodb');
require('dotenv').config();

let credentials = '';
if (process.env.MONGODB_USERNAME) {
if (process.env.MONGODB_PASSWORD) {
credentials = `${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@`;
} else {
credentials = `${process.env.MONGODB_USERNAME}@`;
}
}

const uri = `mongodb://${credentials}${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}/${process.env.MONGODB_DB}`;

module.exports.up = function (next) {
mongodb.MongoClient.connect(uri, { useUnifiedTopology: true })
.then(client => client.db())
.then(db => {
const Games = db.collection('games');
return Games.find().forEach(game => {
game.slots.forEach(slot => {
if (!slot.team) {
slot.team = game.teams[slot.teamId].toLowerCase();
}
});

return Games.save(game);
});
})
.then(next);
}

module.exports.down = next => {
next()
}
83 changes: 83 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@
"dev": "nest start --watch --debug",
"prod": "node dist/main",
"lint": "tslint -p tsconfig.json -c tslint.json",
"test": "jest",
"test": "jest --watch",
"test:ci": "jest --ci --maxWorkers 4",
"console": "ts-node -r tsconfig-paths/register src/console.ts",
"export-skills": "ts-node -r tsconfig-paths/register src/console.ts -- export-skills",
"release": "release-it"
"release": "release-it",
"migrate": "migrate"
},
"dependencies": {
"@hapi/joi": "17.1.1",
Expand All @@ -27,8 +28,8 @@
"@nestjs/platform-express": "7.1.3",
"@nestjs/platform-socket.io": "7.1.3",
"@nestjs/schedule": "0.4.0",
"@nestjs/websockets": "7.1.3",
"@nestjs/serve-static": "2.1.1",
"@nestjs/websockets": "7.1.3",
"@typegoose/typegoose": "7.2.0",
"class-transformer": "0.2.3",
"class-validator": "0.12.2",
Expand All @@ -40,6 +41,7 @@
"jsonschema": "1.2.6",
"jsonwebtoken": "8.5.1",
"lodash": "4.17.15",
"migrate": "^1.6.2",
"moment": "2.26.0",
"mongoose": "5.9.18",
"nestjs-console": "3.0.6",
Expand Down
7 changes: 5 additions & 2 deletions src/games/models/game-player.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { prop, index } from '@typegoose/typegoose';
import { PlayerConnectionStatus } from './player-connection-status';
import { Tf2Team } from './tf2-team';

@index({ playerId: 1 })
@index({ status: 1 })
export class GamePlayer {

@prop({ required: true })
playerId!: string;

@prop({ required: true })
teamId!: string;
@prop({ required: true, enum: Tf2Team })
team!: Tf2Team;

@prop({ required: true })
gameClass!: string;
Expand All @@ -18,4 +20,5 @@ export class GamePlayer {

@prop({ default: 'offline' })
connectionStatus?: PlayerConnectionStatus;

}
5 changes: 2 additions & 3 deletions src/games/models/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,13 @@ type GameState = 'launching' | 'started' | 'ended' | 'interrupted';
@index({ players: 1 })
@index({ gameServer: 1 })
export class Game {

@prop({ default: () => new Date() })
launchedAt?: Date;

@prop({ required: true, unique: true })
number!: number;

@mapProp({ of: String })
teams?: Map<string, string>;

@arrayProp({ ref: 'Player' })
players?: Ref<Player>[];

Expand Down Expand Up @@ -53,4 +51,5 @@ export class Game {

@prop()
stvConnectString?: string;

}
4 changes: 4 additions & 0 deletions src/games/models/tf2-team.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export enum Tf2Team {
Red = 'red',
Blu = 'blu',
};
7 changes: 2 additions & 5 deletions src/games/services/__mocks__/games.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,13 @@ export class GamesService {

async _createOne(players: Player[]) {
let lastTeamId = 0;
const teams = [ 'red', 'blu' ];
return await this.gameModel.create({
number: ++this.lastGameId,
map: 'cp_badlands',
teams: {
0: 'RED',
1: 'BLU',
},
slots: players.map(p => ({
playerId: p.id,
teamId: `${(lastTeamId++) % 2}`,
team: teams[`${(lastTeamId++) % 2}`],
gameClass: 'soldier',
})),
players,
Expand Down
4 changes: 2 additions & 2 deletions src/games/services/game-event-handler.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,11 +223,11 @@ describe('GameEventHandlerService', () => {
it('should update the game\'s score', async () => {
await service.onScoreReported(mockGame.id, 'Red', '2');
let game = await gamesService.getById(mockGame.id);
expect(game.score.get('0')).toEqual(2);
expect(game.score.get('red')).toEqual(2);

await service.onScoreReported(mockGame.id, 'Blue', '5');
game = await gamesService.getById(mockGame.id);
expect(game.score.get('1')).toEqual(5);
expect(game.score.get('blu')).toEqual(5);
});

it('should emit an event over ws', async () => {
Expand Down
16 changes: 3 additions & 13 deletions src/games/services/game-event-handler.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@ export class GameEventHandlerService {

async onMatchStarted(gameId: string) {
const game = await this.gameModel.findOneAndUpdate({ _id: gameId, state: 'launching' }, { state: 'started' });

// const game = await this.gamesService.update({ _id: gameId, state: 'launching' }, { state: 'started' });
if (game) {
this.gamesGateway.emitGameUpdated(game);
}
Expand Down Expand Up @@ -76,18 +74,10 @@ export class GameEventHandlerService {
}

async onScoreReported(gameId: string, teamName: string, score: string) {
const game = await this.gamesService.getById(gameId);
const fixedTeamName = teamName.toLowerCase().substring(0, 3); // converts Red to 'red' and Blue to 'blu'
const game = await this.gameModel.findOneAndUpdate({ _id: gameId }, { [`score.${fixedTeamName}`]: parseInt(score, 10) });
if (game) {
const fixedTeamName = teamName.toUpperCase().substring(0, 3); // converts Red to RED and Blue to BLU
for (const [teamId, name] of game.teams) {
if (name === fixedTeamName) {
game.score = game.score || new Map();
game.score.set(teamId, parseInt(score, 10));
await game.save();
this.gamesGateway.emitGameUpdated(game);
break;
}
}
this.gamesGateway.emitGameUpdated(game);
} else {
this.logger.warn(`no such game: ${gameId}`);
}
Expand Down
Loading

0 comments on commit 3fae9ca

Please sign in to comment.