~bigbes/lethe

ref: ab6efef20d1f15a9c5da17ded758114abb40aeb8 lethe/web/src/features/projects/useProjects.ts -rw-r--r-- 1.4 KiB
ab6efef2 — Eugene Blikh docs: clarify collector plan assumptions 24 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
import { useQuery } from '@tanstack/react-query'
import type { UseQueryResult } from '@tanstack/react-query'
import { apiFetch } from '../../api/client'
import { adaptProject } from '../../api/adapters'
import type { Project, ProjectDTO } from '../../api/adapters'

export interface ProjectFilters {
  since?: '7d' | '30d' | '90d' | 'all'
}

interface ProjectsResponse {
  projects: ProjectDTO[]
  limit: number
  offset: number
}

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

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

export function useProjects(filters: ProjectFilters, options?: UseProjectsOptions): UseQueryResult<Project[]> {
  const since = filters.since ?? '30d'

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

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

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