All files / stream streamVariants.ts

54.83% Statements 17/31
88.88% Branches 16/18
55.55% Functions 5/9
55.17% Lines 16/29

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 52 53 54 55 56                      1x   1x 3x     2x   1x 3x   3x 3x 3x 2x 1x     1x 4x   3x   1x                 1x                        
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { getJson } from './liveApi'
import { ENGAGEMENT_REFRESH_MS, ENGAGEMENT_TIMEOUT_MS } from './ranking'
 
export type Variants = Readonly<Record<string, string>>
 
export interface StreamVariants {
  variants: Variants
  until: number | null
}
 
const MIN_REFETCH_MS = 10_000
 
const isVariants = (value: unknown): value is Variants =>
  typeof value === 'object' &&
  value !== null &&
  !Array.isArray(value) &&
  Object.values(value).every((variant) => typeof variant === 'string')
 
export const parseStreamVariants = (body: unknown): StreamVariants => {
  Iif (typeof body !== 'object' || body === null || !('variants' in body) || !('until' in body))
    throw new Error('Stream variants need variants and an until')
  const { variants, until } = body
  const untilMs = typeof until === 'string' ? Date.parse(until) : Number.NaN
  if (!isVariants(variants) || Number.isNaN(untilMs))
    throw new Error(`The stream variants answer has an unknown shape: ${JSON.stringify(body)}`)
  return { variants, until: untilMs }
}
 
export const refetchDelay = (until: number | null, now: number) =>
  until === null ? ENGAGEMENT_REFRESH_MS : Math.min(ENGAGEMENT_REFRESH_MS, Math.max(MIN_REFETCH_MS, until - now))
 
export const emphasizesHighscore = (variants: Variants) => variants.overlay_emphasis === 'highscore'
 
const fetchStreamVariants = async (): Promise<StreamVariants> => {
  try {
    return parseStreamVariants(await getJson<unknown>('/engagement/variants/stream', ENGAGEMENT_TIMEOUT_MS))
  } catch (error) {
    console.info('The stream variants are unavailable, the overlay keeps its current layout', error)
    return { variants: {}, until: null }
  }
}
 
export const useStreamVariants = () => {
  const variants = ref<Variants>({})
  let timer: number | undefined
  const load = async () => {
    const answer = await fetchStreamVariants()
    variants.value = answer.variants
    timer = window.setTimeout(load, refetchDelay(answer.until, Date.now()))
  }
  onMounted(load)
  onBeforeUnmount(() => window.clearTimeout(timer))
  return variants
}