Skip to content

Commit d7c7877

Browse files
author
Bastien Formery
committed
Fix slow "join game" page
1 parent 318174d commit d7c7877

File tree

5 files changed

+37
-12
lines changed

5 files changed

+37
-12
lines changed

.firebaserc

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"projects": {
3+
"default": "hanabi-df790"
4+
}
5+
}

database.rules.json

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"rules": {
3+
".read": true,
4+
".write": true,
5+
6+
"games": {
7+
".indexOn": ["createdAt"]
8+
}
9+
}
10+
}

firebase.json

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"database": {
3+
"rules": "database.rules.json"
4+
}
5+
}

hooks/firebase.ts

+15-11
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,15 @@ export function setupFirebase() {
3232
return firebase.database();
3333
}
3434

35+
function gameIsPublic(game: IGameState) {
36+
return (
37+
!game.options.private &&
38+
game.status === IGameStatus.LOBBY &&
39+
game.players.length &&
40+
game.players.length < game.playersCount
41+
);
42+
}
43+
3544
export default class FirebaseNetwork implements Network {
3645
db: firebase.database.Database;
3746

@@ -40,21 +49,16 @@ export default class FirebaseNetwork implements Network {
4049
}
4150

4251
subscribeToPublicGames(callback: GamesHandler) {
43-
const ref = this.db.ref("/games");
52+
const ref = this.db
53+
.ref("/games")
54+
// Only games created less than 10 minutes ago
55+
.orderByChild("createdAt")
56+
.startAt(Date.now() - 10 * 60 * 1000);
4457

4558
ref.on("value", event => {
4659
const games = Object.values(event.val() || {})
4760
.map(fillEmptyValues)
48-
// Game is public
49-
.filter(game => !game.options.private)
50-
// Game is in lobby state
51-
.filter(game => game.status === IGameStatus.LOBBY)
52-
// At least one player in the room
53-
.filter(game => game.players.length)
54-
// There are slots remaining
55-
.filter(game => +game.players.length < +game.playersCount)
56-
// The game is recent
57-
.filter(game => game.createdAt > Date.now() - 10 * 60 * 1000);
61+
.filter(gameIsPublic);
5862

5963
callback(games);
6064
});

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
"start": "next start",
99
"server": "firebase-server -p 3001",
1010
"lint": "eslint '**/*.{ts,tsx}'",
11-
"test": "cypress run"
11+
"test": "cypress run",
12+
"deploy-database": "firebase deploy --only database"
1213
},
1314
"dependencies": {
1415
"@types/classnames": "^2.2.9",

0 commit comments

Comments
 (0)