Skip to content

Commit

Permalink
refactor: error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Sn0wye committed May 19, 2024
1 parent cad3fe0 commit 1da35cb
Show file tree
Hide file tree
Showing 14 changed files with 224 additions and 272 deletions.
3 changes: 3 additions & 0 deletions apps/backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { roomRoutes } from './http/routes/room';
import { wsRoutes } from './http/routes/ws';
import { Pubsub } from './lib/pub-sub';
import { authPlugin } from './plugins/auth';
import { fastifyErrorHandler } from './http/error-handler';

// import { csrfPlugin } from './plugins/csrf';
// import { fastifySocketIO } from './plugins/socketio';
Expand Down Expand Up @@ -62,6 +63,8 @@ app.register(fastifySwagger, {
transform: jsonSchemaTransform
});

app.setErrorHandler(fastifyErrorHandler);

app.register(fastifySwaggerUi, {
routePrefix: '/docs'
});
Expand Down
27 changes: 0 additions & 27 deletions apps/backend/src/errors/HTTPError.ts

This file was deleted.

21 changes: 21 additions & 0 deletions apps/backend/src/errors/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export class ApplicationError extends Error {
constructor(message: string) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}

export class BadRequestError extends ApplicationError {}

export class UnauthorizedError extends ApplicationError {
constructor(message?: string) {
super(message ?? 'Unauthorized');
}
}

export class NotFoundError extends ApplicationError {}

export class UnprocessableEntityError extends ApplicationError {}

export class InternalServerError extends ApplicationError {}
4 changes: 3 additions & 1 deletion apps/backend/src/errors/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@ export const ROOM_ERRORS = {
WRONG_PASSWORD:
'Ops... A senha está incorreta! Verifique os dados e tente novamente.',
PLAYER_ALREADY_IN_ROOM:
'Ops... Você não pode entrar em uma sala já estando nela!'
'Ops... Você não pode entrar em uma sala já estando nela!',
NOT_ALL_PLAYERS_READY: 'Oops, nem todos os jogadores estão prontos.',
PLAYER_NOT_FOUND: 'Jogador não encontrado.'
};
53 changes: 24 additions & 29 deletions apps/backend/src/http/controllers/room/create-room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,34 +14,29 @@ export const createRoomController = async (app: App) => {
return res.unauthorized();
}

try {
const validatedBody = createRoom.parse(req.body);

const host: Player = {
id: user.id,
username: user.username,
avatarUrl: user.avatarUrl,
isHost: true,
score: 0,
isReady: false,
isJudge: false
};

const room = await roomService.createRoom({
...validatedBody,
hostId: host.id
});

await roomService.addPlayerToRoom({
roomCode: room.code,
player: host
});

res.status(201);
return room;
} catch (e) {
res.status(400);
return e;
}
const validatedBody = createRoom.parse(req.body);

const host: Player = {
id: user.id,
username: user.username,
avatarUrl: user.avatarUrl,
isHost: true,
score: 0,
isReady: false,
isJudge: false
};

const room = await roomService.createRoom({
...validatedBody,
hostId: host.id
});

await roomService.addPlayerToRoom({
roomCode: room.code,
player: host
});

res.status(201);
return room;
});
};
21 changes: 8 additions & 13 deletions apps/backend/src/http/controllers/room/end-room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,15 @@ export const endRoomController = async (app: App) => {
return res.unauthorized();
}

try {
const { roomCode } = endRoom.parse(req.body);
const { hostId } = await roomService.getRoom(roomCode);
const isAdmin = user.id === hostId;
const { roomCode } = endRoom.parse(req.body);
const { hostId } = await roomService.getRoom(roomCode);
const isAdmin = user.id === hostId;

if (!isAdmin) {
return res.badRequest(ROOM_ERRORS.IS_NOT_ROOM_HOST);
}

const room = await roomService.endRoom(roomCode);
return room;
} catch (e) {
res.status(400);
return e;
if (!isAdmin) {
return res.badRequest(ROOM_ERRORS.IS_NOT_ROOM_HOST);
}

const room = await roomService.endRoom(roomCode);
return room;
});
};
13 changes: 3 additions & 10 deletions apps/backend/src/http/controllers/room/get-room.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { App } from '@/app';
import { HTTPError } from '@/errors/HTTPError';
import { PostgresRoomRepository } from '@/repositories/room/PostgresRoomRepository';
import { RoomService } from '@/services/RoomService';
import { z } from 'zod';
Expand All @@ -22,15 +21,9 @@ export const getRoomController = async (app: App) => {
}

const { roomCode } = req.params;
try {
const { password, ...sanitizedRoom } =
await roomService.getRoom(roomCode);
return sanitizedRoom;
} catch (e) {
if (e instanceof HTTPError) {
return e;
}
}
const { password, ...sanitizedRoom } =
await roomService.getRoom(roomCode);
return sanitizedRoom;
}
);
};
43 changes: 19 additions & 24 deletions apps/backend/src/http/controllers/room/join-room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,33 +22,28 @@ export const joinRoomController = async (app: App) => {
const user = req.user;
const { roomCode, password } = req.body;

try {
const player: Player = {
id: user.id,
isHost: false,
score: 0,
username: user.username,
avatarUrl: user.avatarUrl,
isReady: false,
isJudge: false
};
const player: Player = {
id: user.id,
isHost: false,
score: 0,
username: user.username,
avatarUrl: user.avatarUrl,
isReady: false,
isJudge: false
};

const room = await roomService.joinRoom({
roomCode,
password,
player
});
const room = await roomService.joinRoom({
roomCode,
password,
player
});

app.pubsub.publish(roomCode, {
event: 'player-joined',
payload: player
});
app.pubsub.publish(roomCode, {
event: 'player-joined',
payload: player
});

return room;
} catch (e) {
res.status(400);
return e;
}
return room;
}
);
};
17 changes: 6 additions & 11 deletions apps/backend/src/http/controllers/room/leave-room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,11 @@ export const leaveRoomController = async (app: App) => {
return res.unauthorized();
}

try {
const { roomCode } = leaveRoom.parse(req.body);
await roomService.leaveRoom({
roomCode,
playerId: user.id
});
return res.status(204);
} catch (e) {
res.status(400);
return e;
}
const { roomCode } = leaveRoom.parse(req.body);
await roomService.leaveRoom({
roomCode,
playerId: user.id
});
return res.status(204);
});
};
26 changes: 9 additions & 17 deletions apps/backend/src/http/controllers/room/player-ready.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,17 @@ export const playerReadyController = async (app: App) => {

const { roomCode } = req.params;

try {
const player = await roomService.getPlayerFromRoom(
roomCode,
req.user.id
);
const player = await roomService.getPlayerFromRoom(roomCode, req.user.id);

await roomService.updatePlayerInRoom(roomCode, req.user.id, {
isReady: !player.isReady
});
player.isReady = !player.isReady;
await roomService.updatePlayerInRoom(roomCode, req.user.id, {
isReady: !player.isReady
});
player.isReady = !player.isReady;

await app.pubsub.publish(roomCode, {
event: 'player-update',
payload: player
});
} catch (e) {
console.error(e);
return e;
}
await app.pubsub.publish(roomCode, {
event: 'player-update',
payload: player
});
}
);
};
75 changes: 34 additions & 41 deletions apps/backend/src/http/controllers/room/start-room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,55 +17,48 @@ export const startRoomController = async (app: App) => {
return res.unauthorized();
}

try {
const { roomCode } = startRoom.parse(req.body);
const cardService = new CardService(roomCode, basePack);
let room = await roomService.getRoom(roomCode);
const { roomCode } = startRoom.parse(req.body);
const cardService = new CardService(roomCode, basePack);
let room = await roomService.getRoom(roomCode);

if (user.id !== room.hostId) {
return res.badRequest(ROOM_ERRORS.IS_NOT_ROOM_HOST);
}

const players = await roomService.getRoomPlayers(roomCode);
const judgeId = getRandomJudge(room.prevJudgeId, players);
if (user.id !== room.hostId) {
return res.badRequest(ROOM_ERRORS.IS_NOT_ROOM_HOST);
}

room = await roomService.updateRoom(roomCode, {
judgeId,
status: 'IN_PROGRESS',
round: room.round + 1
});
const players = await roomService.getRoomPlayers(roomCode);
const judgeId = getRandomJudge(room.prevJudgeId, players);

await roomService.updatePlayerInRoom(roomCode, judgeId, {
isJudge: true
});
room = await roomService.updateRoom(roomCode, {
judgeId,
status: 'IN_PROGRESS',
round: room.round + 1
});

await app.pubsub.publish(roomCode, {
event: 'room-started',
payload: room
});
await roomService.updatePlayerInRoom(roomCode, judgeId, {
isJudge: true
});

const playersWithoutJudge = players.filter(
player => player.id !== judgeId
);
await app.pubsub.publish(roomCode, {
event: 'room-started',
payload: room
});

const blackCards = await cardService.getNewBlackCards(1);
await app.pubsub.publish(roomCode, {
event: 'black-card-drawn',
payload: blackCards[0]
});
const playersWithoutJudge = players.filter(player => player.id !== judgeId);

for (const player of playersWithoutJudge) {
const whiteCards = await cardService.getNewWhiteCards(6);
await app.pubsub.publish(player.id, {
event: 'cards-drawn',
payload: whiteCards
});
}
const blackCards = await cardService.getNewBlackCards(1);
await app.pubsub.publish(roomCode, {
event: 'black-card-drawn',
payload: blackCards[0]
});

res.status(204);
} catch (e) {
res.status(400);
return e;
for (const player of playersWithoutJudge) {
const whiteCards = await cardService.getNewWhiteCards(6);
await app.pubsub.publish(player.id, {
event: 'cards-drawn',
payload: whiteCards
});
}

res.status(204);
});
};
Loading

0 comments on commit 1da35cb

Please sign in to comment.