useQueryInsightsScore.ts49 lines · main
1import { useMemo } from 'react'
2
3import {
4 HIGH_CALL_THRESHOLD,
5 SCORE_DEDUCTIONS,
6} from '../QueryInsightsHealth/QueryInsightsHealth.constants'
7import type { ClassifiedQuery } from '../QueryInsightsHealth/QueryInsightsHealth.types'
8import { getHealthLevel } from '../QueryInsightsHealth/QueryInsightsHealth.utils'
9
10export function useQueryInsightsScore({
11 errors,
12 indexIssues,
13 slowQueries,
14}: {
15 errors: ClassifiedQuery[]
16 indexIssues: ClassifiedQuery[]
17 slowQueries: ClassifiedQuery[]
18}) {
19 return useMemo(() => {
20 let score = 100
21
22 score -= errors.length * SCORE_DEDUCTIONS.error
23
24 score -= indexIssues.reduce(
25 (acc, q) =>
26 acc +
27 (q.calls > HIGH_CALL_THRESHOLD
28 ? SCORE_DEDUCTIONS.indexHighCalls
29 : SCORE_DEDUCTIONS.indexLowCalls),
30 0
31 )
32
33 score -= slowQueries.reduce(
34 (acc, q) =>
35 acc +
36 (q.calls > HIGH_CALL_THRESHOLD / 2
37 ? SCORE_DEDUCTIONS.slowHighCalls
38 : SCORE_DEDUCTIONS.slowLowCalls),
39 0
40 )
41
42 score = Math.max(0, Math.min(100, score))
43
44 return {
45 score,
46 level: getHealthLevel(score),
47 }
48 }, [errors, indexIssues, slowQueries])
49}