Skip to content

Commit

Permalink
types: Use enums for App event types.
Browse files Browse the repository at this point in the history
  • Loading branch information
kuv2707 committed Jun 21, 2024
1 parent 6faf6ee commit 0b12974
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 32 deletions.
9 changes: 5 additions & 4 deletions backend/src/controllers/gameControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { enqueueForSend } from '../eventRecipients';
import { AuthRequest } from '../middlewares/authMiddleware';
import { createGame, retrieveGame } from '../gameStore';
import { GameEngine } from '../uno-game-engine/engine';
import { GameEventTypes } from '../types';

export async function handleGameEvent(req: AuthRequest, res: Response) {
const event = req.body;
Expand Down Expand Up @@ -48,7 +49,7 @@ export async function handleGameJoin(req: AuthRequest, res: Response) {
//note: when retrieving game from database, it is not an instance of GameEngine
// we'd need to add these functions to the mongodb game schema
// this should be sent once the joining player receives the game state
game.dispatchEvent({ type: 'JOIN_GAME', playerId: req.user.id });
game.dispatchEvent({ type: GameEventTypes.JOIN_GAME, playerId: req.user.id });
propagateChanges(game);
req.user.activeGameId = gameCode;
await req.user.save();
Expand All @@ -61,8 +62,8 @@ export async function handleGameJoin(req: AuthRequest, res: Response) {
export async function handleGameCreate(req: AuthRequest, res: Response) {
const game = createGame();
const eventResult = game.dispatchEvent({
type: 'JOIN_GAME',
playerId: req.user.id,
type: GameEventTypes.JOIN_GAME,
playerId: req.user.id as string,
});
if (eventResult.type === 'ERROR') {
res.status(500).send({ message: 'Failed to create game' });
Expand All @@ -84,7 +85,7 @@ function propagateChanges(game: GameEngine) {
// Instead, we can just send the new game state to the clients.
for (const player of game.players) {
enqueueForSend(player.id, {
type: 'STATE_SYNC',
type: GameEventTypes.STATE_SYNC,
data: {
players: game.players,
cards: game.cardDeck,
Expand Down
34 changes: 23 additions & 11 deletions backend/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,38 +42,41 @@ export type EventResult = {
message: string;
};

export type GameEventType =
| 'DRAW_CARD'
| 'THROW_CARD'
| 'JOIN_GAME'
| 'LEAVE_GAME'
| 'STATE_SYNC';
export enum GameEventTypes {
DRAW_CARD = 'DRAW_CARD',
THROW_CARD = 'THROW_CARD',
JOIN_GAME = 'JOIN_GAME',
LEAVE_GAME = 'LEAVE_GAME',
STATE_SYNC = 'STATE_SYNC',
}

export type GameEvent =
| {
type: 'DRAW_CARD';
type: GameEventTypes.DRAW_CARD;
playerId: string;
data: {
cardId: string;
};
}
| {
type: 'THROW_CARD';
type: GameEventTypes.THROW_CARD;
playerId: string;
data: {
cardId: string;
};
}
| {
type: 'JOIN_GAME';
type: GameEventTypes.JOIN_GAME;
playerId: string;
data?: null;
}
| {
type: 'LEAVE_GAME';
type: GameEventTypes.LEAVE_GAME;
playerId: string;
data?: null;
}
| {
type: 'STATE_SYNC';
type: GameEventTypes.STATE_SYNC;
data: {
players: Player[];
cards: UNOCard[];
Expand All @@ -82,6 +85,15 @@ export type GameEvent =
};
};

export enum ChatEventTypes {
SEND_MESSAGE = 'SEND_MESSAGE',
REACT_TO_MESSAGE = 'REACT_TO_MESSAGE',
DELETE_MESSAGE = 'DELETE_MESSAGE',
EDIT_MESSAGE = 'EDIT_MESSAGE',
}

export type AppEventType = GameEventTypes | ChatEventTypes;

// Represent all the events that can be sent to the client
// a workaround for now to make things work - this will be refactored later
export type AppEvent = GameEvent;
Expand Down
4 changes: 2 additions & 2 deletions backend/src/uno-game-engine/events/drawCard.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { GameEngine } from '../engine';
import assert from 'assert';
import { canThrowCard, throwCard } from './throwCard';
import { EventResult, GameEvent } from '../../types';
import { EventResult, GameEvent, GameEventTypes } from '../../types';
import { checkCurrentPlayer, getPlayer } from './eventHandlerUtils';

export function drawCard(game: GameEngine, event: GameEvent): EventResult {
Expand All @@ -28,7 +28,7 @@ export function drawCard(game: GameEngine, event: GameEvent): EventResult {
const canThrow = canThrowCard(game, player, drawnCard);
if (canThrow.type === 'SUCCESS') {
throwCard(game, {
type: 'THROW_CARD',
type: GameEventTypes.THROW_CARD,
playerId: player.id,
data: {
cardId: drawnCard.id,
Expand Down
14 changes: 7 additions & 7 deletions backend/src/uno-game-engine/gameEvents.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// this module houses the handlers for various game events.

import { EventResult, GameEvent, GameEventType } from '../types';
import { EventResult, GameEvent, GameEventTypes } from '../types';
import { type GameEngine } from './engine';
import { drawCard } from './events/drawCard';
import { joinGame } from './events/joinGame';
Expand All @@ -9,10 +9,10 @@ import { throwCard } from './events/throwCard';

type GameEventHandler = (game: GameEngine, event: GameEvent) => EventResult;

const map = new Map<GameEventType, GameEventHandler>();
const map = new Map<GameEventTypes, GameEventHandler>();

export function registerEventHandler(
eventType: GameEventType,
eventType: GameEventTypes,
handler: GameEventHandler
) {
map.set(eventType, handler);
Expand All @@ -26,7 +26,7 @@ export function handleEvent(game: GameEngine, event: GameEvent): EventResult {
return handler(game, event);
}

registerEventHandler('JOIN_GAME', joinGame);
registerEventHandler('LEAVE_GAME', leaveGame);
registerEventHandler('DRAW_CARD', drawCard);
registerEventHandler('THROW_CARD', throwCard);
registerEventHandler(GameEventTypes.JOIN_GAME, joinGame);
registerEventHandler(GameEventTypes.LEAVE_GAME, leaveGame);
registerEventHandler(GameEventTypes.DRAW_CARD, drawCard);
registerEventHandler(GameEventTypes.THROW_CARD, throwCard);
10 changes: 4 additions & 6 deletions frontend/src/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export function stopPolling() {
}
}

export function triggerEvent(type: types.GameEventType, data?: unknown) {
export function triggerEvent(event: Omit<types.AppEvent, 'playerId'>) {
if (!authCreds) {
throw new Error('Auth credentials not set');
}
Expand All @@ -106,11 +106,9 @@ export function triggerEvent(type: types.GameEventType, data?: unknown) {
Authorization: authCreds.jwt,
},
body: JSON.stringify({
event: {
type,
playerId: authCreds.playerId,
data,
},
type: event.type,
playerId: authCreds.playerId,
data: event.data,
}),
}).catch((e) => {
console.error('Error triggering event:', e);
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export function AuthProvider({ children }: { children: ReactElement }) {
name: data.user.username,
});
setJwt(localToken!);
channel.setAuthCreds(localToken!, data.user.id);
channel.setAuthCreds(localToken!, data.user._id);
channel.startPolling();
}
} catch (e) {
Expand Down Expand Up @@ -106,7 +106,7 @@ export function AuthProvider({ children }: { children: ReactElement }) {
});
setJwt(data.token);
localStorage.setItem('jwt', data.token);
channel.setAuthCreds(data.token, data.user.id);
channel.setAuthCreds(data.token, data.user._id);
channel.startPolling();
},
[setUser, toast]
Expand Down

0 comments on commit 0b12974

Please sign in to comment.