tooot/src/utils/queryHooks/status.ts

62 lines
1.7 KiB
TypeScript
Raw Normal View History

import { QueryFunctionContext, useQuery, UseQueryOptions } from '@tanstack/react-query'
2023-01-03 23:57:23 +01:00
import apiGeneral from '@utils/api/general'
import apiInstance from '@utils/api/instance'
import { appendRemote } from '@utils/helpers/appendRemote'
2023-01-03 23:57:23 +01:00
import { urlMatcher } from '@utils/helpers/urlMatcher'
import { AxiosError } from 'axios'
2023-01-03 23:57:23 +01:00
import { searchLocalStatus } from './search'
2022-11-12 17:52:50 +01:00
2023-01-03 23:57:23 +01:00
export type QueryKeyStatus = [
'Status',
(Pick<Mastodon.Status, 'uri'> & Partial<Pick<Mastodon.Status, 'id' | '_remote'>>) | undefined
]
2022-11-12 17:52:50 +01:00
const queryFunction = async ({ queryKey }: QueryFunctionContext<QueryKeyStatus>) => {
2023-01-03 23:57:23 +01:00
const key = queryKey[1]
if (!key) return Promise.reject()
2022-11-12 17:52:50 +01:00
2023-01-03 23:57:23 +01:00
let matchedStatus: Mastodon.Status | undefined = undefined
const match = urlMatcher(key.uri)
const domain = match?.domain
const id = key.id || match?.status?.id
if (key._remote && domain && id) {
try {
matchedStatus = await apiGeneral<Mastodon.Status>({
method: 'get',
domain,
url: `api/v1/statuses/${id}`
2023-02-25 23:42:04 +01:00
}).then(res => appendRemote.status(res.body, domain))
2023-01-03 23:57:23 +01:00
} catch {}
}
if (!matchedStatus && !key._remote && id) {
matchedStatus = await apiInstance<Mastodon.Status>({
method: 'get',
url: `statuses/${id}`
}).then(res => res.body)
}
if (!matchedStatus) {
matchedStatus = await searchLocalStatus(key.uri)
}
return matchedStatus
2022-11-12 17:52:50 +01:00
}
const useStatusQuery = ({
options,
2023-01-03 23:57:23 +01:00
status
}: { status?: QueryKeyStatus[1] } & {
2022-11-12 17:52:50 +01:00
options?: UseQueryOptions<Mastodon.Status, AxiosError>
}) => {
2023-01-03 23:57:23 +01:00
const queryKey: QueryKeyStatus = [
'Status',
status ? { id: status.id, uri: status.uri, _remote: status._remote } : undefined
]
2022-11-12 17:52:50 +01:00
return useQuery(queryKey, queryFunction, options)
}
export { useStatusQuery }