2021-02-20 19:12:44 +01:00
|
|
|
import apiInstance from '@api/instance'
|
2021-01-07 19:13:09 +01:00
|
|
|
import { AxiosError } from 'axios'
|
|
|
|
import { useQuery, UseQueryOptions } from 'react-query'
|
|
|
|
|
|
|
|
export type QueryKey = [
|
|
|
|
'Search',
|
|
|
|
{
|
|
|
|
type?: 'accounts' | 'hashtags' | 'statuses'
|
|
|
|
term?: string
|
|
|
|
limit?: number
|
|
|
|
}
|
|
|
|
]
|
|
|
|
|
|
|
|
type SearchResult = {
|
|
|
|
accounts: Mastodon.Account[]
|
|
|
|
hashtags: Mastodon.Tag[]
|
|
|
|
statuses: Mastodon.Status[]
|
|
|
|
}
|
|
|
|
|
|
|
|
const queryFunction = ({ queryKey }: { queryKey: QueryKey }) => {
|
|
|
|
const { type, term, limit = 20 } = queryKey[1]
|
2021-02-20 19:12:44 +01:00
|
|
|
return apiInstance<SearchResult>({
|
2021-01-07 19:13:09 +01:00
|
|
|
version: 'v2',
|
|
|
|
method: 'get',
|
|
|
|
url: 'search',
|
|
|
|
params: { ...(type && { type }), ...(term && { q: term }), limit }
|
2021-02-11 01:33:31 +01:00
|
|
|
}).then(res => res.body)
|
2021-01-07 19:13:09 +01:00
|
|
|
}
|
|
|
|
|
2021-01-11 21:36:57 +01:00
|
|
|
const useSearchQuery = <TData = SearchResult>({
|
2021-01-07 19:13:09 +01:00
|
|
|
options,
|
|
|
|
...queryKeyParams
|
|
|
|
}: QueryKey[1] & {
|
|
|
|
options?: UseQueryOptions<SearchResult, AxiosError, TData>
|
|
|
|
}) => {
|
|
|
|
const queryKey: QueryKey = ['Search', { ...queryKeyParams }]
|
|
|
|
return useQuery(queryKey, queryFunction, options)
|
|
|
|
}
|
|
|
|
|
2021-01-11 21:36:57 +01:00
|
|
|
export { useSearchQuery }
|