mirror of https://github.com/tooot-app/app
65 lines
1.5 KiB
TypeScript
65 lines
1.5 KiB
TypeScript
import { QueryFunctionContext, useQuery, UseQueryOptions } from '@tanstack/react-query'
|
|
import apiInstance from '@utils/api/instance'
|
|
import { AxiosError } from 'axios'
|
|
|
|
export type QueryKeySearch = [
|
|
'Search',
|
|
{
|
|
type?: 'accounts' | 'hashtags' | 'statuses'
|
|
term?: string
|
|
limit?: number
|
|
}
|
|
]
|
|
|
|
export type SearchResult = {
|
|
accounts: Mastodon.Account[]
|
|
hashtags: Mastodon.Tag[]
|
|
statuses: Mastodon.Status[]
|
|
}
|
|
|
|
const queryFunction = async ({ queryKey }: QueryFunctionContext<QueryKeySearch>) => {
|
|
const { type, term, limit = 20 } = queryKey[1]
|
|
if (!term?.length) {
|
|
return Promise.reject('Empty search term')
|
|
}
|
|
const res = await apiInstance<SearchResult>({
|
|
version: 'v2',
|
|
method: 'get',
|
|
url: 'search',
|
|
params: {
|
|
q: term,
|
|
...(type && { type }),
|
|
limit,
|
|
resolve: true
|
|
}
|
|
})
|
|
return res.body
|
|
}
|
|
|
|
const useSearchQuery = <T = SearchResult>({
|
|
options,
|
|
...queryKeyParams
|
|
}: QueryKeySearch[1] & {
|
|
options?: UseQueryOptions<SearchResult, AxiosError, T>
|
|
}) => {
|
|
const queryKey: QueryKeySearch = ['Search', { ...queryKeyParams }]
|
|
return useQuery(queryKey, queryFunction, options)
|
|
}
|
|
|
|
export const searchFetchToot = (uri: Mastodon.Status['uri']): Promise<Mastodon.Status | void> =>
|
|
apiInstance<SearchResult>({
|
|
version: 'v2',
|
|
method: 'get',
|
|
url: 'search',
|
|
params: {
|
|
q: uri,
|
|
type: 'statuses',
|
|
limit: 1,
|
|
resolve: true
|
|
}
|
|
})
|
|
.then(res => res.body.statuses[0])
|
|
.catch(err => console.warn(err))
|
|
|
|
export { useSearchQuery }
|