~bigbes/lethe

ref: f0f651bfc74681988f56bd610074e1dce6dbee1c lethe/web/src/features/home/useSessions.ts -rw-r--r-- 1.7 KiB
f0f651bf — Eugene Blikh feat: add search data layer — adapter, highlight helper, hook, and tests 23 days ago
                                                                                
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
57
58
59
60
61
62
63
64
65
import { useQuery } from '@tanstack/react-query'
import type { UseQueryResult } from '@tanstack/react-query'
import { apiFetch } from '../../api/client'
import { adaptSession } from '../../api/adapters'
import type { Session, SessionDTO, Tool, Host } from '../../api/adapters'

export interface HomeFilters {
  since?: '1d' | '7d' | '30d' | '90d' | 'all'
  tool?: Tool
  host?: Host
  cwd?: string
}

interface SessionsResponse {
  sessions: SessionDTO[]
  limit: number
  offset: number
}

function sinceToEpoch(since: string): number {
  const now = Math.floor(Date.now() / 1000)
  switch (since) {
    case '1d':  return now - 1 * 86400
    case '7d':  return now - 7 * 86400
    case '30d': return now - 30 * 86400
    case '90d': return now - 90 * 86400
    default:    return 0
  }
}

export interface UseSessionsOptions {
  enabled?: boolean
  staleTime?: number
}

export function useSessions(filters: HomeFilters, options?: UseSessionsOptions): UseQueryResult<Session[]> {
  const since = filters.since ?? '30d'

  return useQuery({
    queryKey: ['sessions', filters],
    queryFn: async () => {
      const params = new URLSearchParams()

      if (since !== 'all') {
        params.set('since', String(sinceToEpoch(since)))
      }
      if (filters.tool) {
        params.set('tool', filters.tool)
      }
      if (filters.host) {
        params.set('host', filters.host)
      }
      if (filters.cwd) {
        params.set('cwd', filters.cwd)
      }

      const qs = params.toString()
      const url = `/api/v1/sessions${qs ? `?${qs}` : ''}`
      const data = await apiFetch<SessionsResponse>(url)
      return data.sessions.map(adaptSession)
    },
    enabled: options?.enabled,
    staleTime: options?.staleTime,
  })
}