-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(search): move matchmaking logic inside a custom hook
- Loading branch information
Showing
2 changed files
with
69 additions
and
57 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import { useEffect, useState } from 'react' | ||
import { useTransmit } from '~/hooks/use_transmit' | ||
import { useTranslation } from 'react-i18next' | ||
import { Api } from '~/services/api' | ||
import { router } from '@inertiajs/react' | ||
import type { SearchProps } from '~/pages/search' | ||
|
||
export const useMatchmaking = (props: SearchProps) => { | ||
const { user, existingSession } = props | ||
const [queueCount, setQueueCount] = useState(0) | ||
const { subscription: userListener } = useTransmit({ url: `game/user/${user.id}` }) | ||
const { subscription: queueListener } = useTransmit({ url: 'game/search' }) | ||
|
||
const { t } = useTranslation() | ||
|
||
const registerToQueue = async () => { | ||
const response: { message: string; queueCount: number } = await new Api().post('/game/search') | ||
setQueueCount(response.queueCount) | ||
} | ||
|
||
useEffect(() => { | ||
if (existingSession) { | ||
router.visit(`/game/session/${existingSession}`) | ||
return | ||
} | ||
registerToQueue() | ||
}, []) | ||
|
||
userListener?.create() | ||
queueListener?.create() | ||
|
||
userListener?.onMessage(async (message: { status: string; sessionId: string }) => { | ||
if (message.status === 'accept') { | ||
await new Api().get(`/game/session/${message.sessionId}/accept`) | ||
return | ||
} | ||
|
||
if (message.status === 'removed') { | ||
await queueListener?.delete() | ||
await userListener?.delete() | ||
return router.visit('/game') | ||
} | ||
|
||
if (message.status === 'start') { | ||
return router.visit(`/game/session/${message.sessionId}`) | ||
} | ||
}) | ||
|
||
queueListener?.onMessage((message: { queueCount: number }) => { | ||
setQueueCount(message.queueCount) | ||
}) | ||
|
||
const cancelQueue = async () => { | ||
await new Api().delete('/game/search') | ||
await queueListener?.delete() | ||
await userListener?.delete() | ||
return router.visit('/game') | ||
} | ||
|
||
return { | ||
cancelQueue, | ||
queueCount, | ||
t, | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters