summaryrefslogtreecommitdiff
path: root/apps/web/lib/queries/use-entry-search.ts
blob: 9e05ac849ed6e13fa82c7df4f5a471ea444509bd (plain) (blame)
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
"use client"

import { useQuery } from "@tanstack/react-query"
import { createSupabaseBrowserClient } from "@/lib/supabase/client"
import { queryKeys } from "./query-keys"
import type { TimelineEntry } from "@/lib/types/timeline"

interface SearchResultRow {
  entry_id: string
  feed_id: string
  feed_title: string
  custom_title: string | null
  entry_title: string
  entry_url: string
  author: string | null
  summary: string | null
  image_url: string | null
  published_at: string
  is_read: boolean
  is_saved: boolean
}

export function useEntrySearch(searchQuery: string) {
  const supabaseClient = createSupabaseBrowserClient()
  const trimmedQuery = searchQuery.trim()

  return useQuery({
    queryKey: queryKeys.entrySearch.query(trimmedQuery),
    queryFn: async () => {
      const { data, error } = await supabaseClient.rpc("search_entries", {
        p_query: trimmedQuery,
        p_result_limit: 30,
      })

      if (error) throw error

      return ((data as SearchResultRow[]) ?? []).map(
        (row): TimelineEntry => ({
          entryIdentifier: row.entry_id,
          feedIdentifier: row.feed_id,
          feedTitle: row.feed_title,
          customTitle: row.custom_title,
          entryTitle: row.entry_title,
          entryUrl: row.entry_url,
          author: row.author,
          summary: row.summary,
          imageUrl: row.image_url,
          publishedAt: row.published_at,
          isRead: row.is_read,
          isSaved: row.is_saved,
          enclosureUrl: null,
          enclosureType: null,
        })
      )
    },
    enabled: trimmedQuery.length >= 2,
  })
}