tooot/src/utils/queryHooks/search.ts

49 lines
1.1 KiB
TypeScript
Raw Normal View History

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'
2021-12-18 19:59:38 +01:00
import { QueryFunctionContext, useQuery, UseQueryOptions } from 'react-query'
2021-01-07 19:13:09 +01:00
2021-12-18 19:59:38 +01:00
export type QueryKeySearch = [
2021-01-07 19:13:09 +01:00
'Search',
{
type?: 'accounts' | 'hashtags' | 'statuses'
term?: string
limit?: number
}
]
2021-03-21 23:06:53 +01:00
export type SearchResult = {
2021-01-07 19:13:09 +01:00
accounts: Mastodon.Account[]
hashtags: Mastodon.Tag[]
statuses: Mastodon.Status[]
}
2021-12-18 19:59:38 +01:00
const queryFunction = async ({
queryKey
}: QueryFunctionContext<QueryKeySearch>) => {
2021-01-07 19:13:09 +01:00
const { type, term, limit = 20 } = queryKey[1]
2021-12-18 19:59:38 +01:00
const res = await apiInstance<SearchResult>({
2021-01-07 19:13:09 +01:00
version: 'v2',
method: 'get',
url: 'search',
2021-03-21 23:06:53 +01:00
params: {
...(type && { type }),
...(term && { q: term }),
limit,
resolve: true
}
2021-12-18 19:59:38 +01:00
})
return res.body
2021-01-07 19:13:09 +01:00
}
2021-12-18 19:59:38 +01:00
const useSearchQuery = <T = unknown>({
2021-01-07 19:13:09 +01:00
options,
...queryKeyParams
2021-12-18 19:59:38 +01:00
}: QueryKeySearch[1] & {
options?: UseQueryOptions<SearchResult, AxiosError, T>
2021-01-07 19:13:09 +01:00
}) => {
2021-12-18 19:59:38 +01:00
const queryKey: QueryKeySearch = ['Search', { ...queryKeyParams }]
2021-01-07 19:13:09 +01:00
return useQuery(queryKey, queryFunction, options)
}
2021-01-11 21:36:57 +01:00
export { useSearchQuery }