~bigbes/lethe

ref: dcafcb245c4d2e39d35dc6be5c9c301a8e66e6a2 lethe/web/src/features/projects/useProjects.ts -rw-r--r-- 1.2 KiB
dcafcb24 — Eugene Blikh web: add lambda favicon (svg + ico + apple-touch-icon) a month 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
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 function useProjects(filters: ProjectFilters): 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)
    },
  })
}