Skip to content

Commit

Permalink
IDA-503: migrate max players update to server action
Browse files Browse the repository at this point in the history
- Add server action for updating room capacity
- Create Zod schema for input validation
- Migrate lobby component from direct DB queries
- Add error handling with toast notifications
  • Loading branch information
RickyRAV committed Jan 9, 2025
1 parent f597f52 commit 87cc55d
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 31 deletions.
21 changes: 21 additions & 0 deletions apps/dashboard/src/app/actions/rooms/update-capacity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"use server";

import { actionClient } from "../safe-action";
import { updateMaxPlayersSchema } from "../schemas/update-max-players-schema";
import { db } from "@/db";
import { rooms } from "@drizzle/schema";
import { eq } from "drizzle-orm";

export const updateRoomMaxPlayers = actionClient
.schema(updateMaxPlayersSchema)
.action(async ({ parsedInput: { maxPlayers, roomCode } }) => {
const updated = await db
.update(rooms)
.set({ maxPlayers })
.where(eq(rooms.code, roomCode))
.returning({ maxPlayers: rooms.maxPlayers });

if (!updated[0]) throw new Error("Failed to update room capacity");

return { maxPlayers: updated[0].maxPlayers };
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { z } from "zod";
import {roomSchema} from "@/app/api/v1/schemas"

export const updateMaxPlayersSchema = z.object({
maxPlayers: z.number().min(2).max(10),
roomCode: roomSchema.shape.roomCode,
});
59 changes: 28 additions & 31 deletions apps/dashboard/src/components/multiplayer-page/lobby.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ import { Player, useMultiplayer } from '@/contexts/multiplayer-context';
import { ScrollArea } from '@/components/ui/scroll-area';
import { User } from '@/contexts/user-context';
import { RealtimeChannel } from '@supabase/supabase-js';
import { useAction } from 'next-safe-action/hooks';
import { updateRoomMaxPlayers } from '@/app/actions/rooms/update-capacity';
import { useToast } from '@/components/ui/use-toast';

interface PresenceData {
currentUser: {
id: string;
Expand Down Expand Up @@ -55,6 +59,7 @@ export default function Lobby() {
const router = useRouter();
const roomCode = routerParams['roomCode'] as string;
const supabase = createClient();
const {toast} = useToast();

const checkAndJoinRoom = async (channel: RealtimeChannel) => {
try {
Expand Down Expand Up @@ -224,40 +229,32 @@ export default function Lobby() {
}
}, [players]);

const changeAmountOfPlayers = async (newAmount: number) => {
if (!channel) {
console.error('Channel is not initialized.');
return;
}
const updatePlayersAction = useAction(updateRoomMaxPlayers, {
onError: () => {
toast({
duration: 3500,
variant: 'destructive',
title: 'Something went wrong.',
});
},
});

if (Number.isNaN(newAmount) || newAmount < 2) {
return;
}
const changeAmountOfPlayers = async (newAmount: number) => {
if (!channel || !isCreator) return;

try {
if (isCreator) {
// Update database

const { data, error } = await supabase
.from('rooms')
.update({ max_players: newAmount })
.eq('code', roomCode)
.select()
.single();
const result = await updatePlayersAction.execute({
roomCode,
maxPlayers: newAmount
});

console.log(data);
if (error) throw error;

// Update local state and broadcast to others
if (data) {
setMaxPlayers(newAmount);
await channel.send({
type: 'broadcast',
event: 'change-amount-of-players',
payload: { newAmount },
});
}
}
// Update local state and broadcast to others
setMaxPlayers(newAmount);
await channel.send({
type: 'broadcast',
event: 'change-amount-of-players',
payload: { newAmount },
});
} catch (error) {
console.error('Failed to update max players:', error);
}
Expand Down Expand Up @@ -489,4 +486,4 @@ export default function Lobby() {
</div>
</div>
);
}
}
15 changes: 15 additions & 0 deletions package-lock.json

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

0 comments on commit 87cc55d

Please sign in to comment.