All files / web/src/hooks useRecordGameResult.ts

100% Statements 51/51
87.5% Branches 7/8
100% Functions 4/4
100% Lines 51/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 521x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 7x 7x 7x 7x 7x 7x 7x 3x 3x 3x 4x 4x 7x 15x 15x 4x 4x 4x 4x 4x 15x 15x 3x 3x 15x 15x  
'use client'
 
import { useMutation, useQueryClient } from '@tanstack/react-query'
import type { GameResult, RecordGameResponse } from '@/lib/arcade/stats/types'
import { api } from '@/lib/queryClient'
 
/**
 * Hook to record a game result and update player stats
 *
 * Usage:
 * ```tsx
 * const { mutate: recordGame, isPending } = useRecordGameResult()
 *
 * recordGame(gameResult, {
 *   onSuccess: (updates) => {
 *     console.log('Stats recorded:', updates)
 *   }
 * })
 * ```
 */
export function useRecordGameResult() {
  const queryClient = useQueryClient()
 
  return useMutation({
    mutationFn: async (gameResult: GameResult): Promise<RecordGameResponse> => {
      const res = await api('player-stats/record-game', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ gameResult }),
      })
 
      if (!res.ok) {
        const error = await res.json().catch(() => ({ error: 'Failed to record game result' }))
        throw new Error(error.error || 'Failed to record game result')
      }
 
      return res.json()
    },
 
    onSuccess: (response) => {
      // Invalidate player stats queries to trigger refetch
      queryClient.invalidateQueries({ queryKey: ['player-stats'] })
 
      console.log('✅ Game result recorded successfully:', response.updates)
    },
 
    onError: (error) => {
      console.error('❌ Failed to record game result:', error)
    },
  })
}