tooot/src/utils/queryHooks/tags.ts

77 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-11-20 16:14:08 +01:00
import {
QueryFunctionContext,
2022-12-10 20:19:18 +01:00
useInfiniteQuery,
UseInfiniteQueryOptions,
2022-11-20 16:14:08 +01:00
useMutation,
UseMutationOptions,
useQuery,
UseQueryOptions
} from '@tanstack/react-query'
import { PagedResponse } from '@utils/api/helpers'
import apiInstance from '@utils/api/instance'
import { featureCheck } from '@utils/helpers/featureCheck'
import { AxiosError } from 'axios'
2022-12-10 20:19:18 +01:00
import { infinitePageParams } from './utils'
2022-11-20 16:14:08 +01:00
2022-12-10 20:19:18 +01:00
export type QueryKeyFollowedTags = ['FollowedTags']
const useFollowedTagsQuery = (
params: {
options?: Omit<
2022-12-15 14:28:36 +01:00
UseInfiniteQueryOptions<PagedResponse<Mastodon.Tag[]>, AxiosError>,
2022-12-10 20:19:18 +01:00
'getPreviousPageParam' | 'getNextPageParam'
>
} | void
) => {
const canFollowTags = featureCheck('follow_tags')
2022-12-25 17:40:53 +01:00
2022-11-20 16:14:08 +01:00
const queryKey: QueryKeyFollowedTags = ['FollowedTags']
2022-12-10 20:19:18 +01:00
return useInfiniteQuery(
2022-11-20 16:14:08 +01:00
queryKey,
async ({ pageParam }: QueryFunctionContext<QueryKeyFollowedTags>) => {
const params: { [key: string]: string } = { ...pageParam }
2022-12-25 17:40:53 +01:00
return await apiInstance<Mastodon.Tag[]>({
method: 'get',
url: `followed_tags`,
params: { limit: 200, ...params }
})
2022-11-20 16:14:08 +01:00
},
2022-12-10 20:19:18 +01:00
{
2022-12-25 17:40:53 +01:00
enabled: canFollowTags,
staleTime: Infinity,
cacheTime: Infinity,
2022-12-10 20:19:18 +01:00
...params?.options,
...infinitePageParams
}
2022-11-20 16:14:08 +01:00
)
}
2022-12-10 20:19:18 +01:00
export type QueryKeyTags = ['Tags', { tag: string }]
const queryFunction = async ({ queryKey }: QueryFunctionContext<QueryKeyTags>) => {
2022-11-20 16:14:08 +01:00
const { tag } = queryKey[1]
const res = await apiInstance<Mastodon.Tag>({ method: 'get', url: `tags/${tag}` })
return res.body
2022-11-20 16:14:08 +01:00
}
const useTagsQuery = ({
options,
...queryKeyParams
}: QueryKeyTags[1] & {
options?: UseQueryOptions<Mastodon.Tag, AxiosError>
}) => {
const queryKey: QueryKeyTags = ['Tags', { ...queryKeyParams }]
return useQuery(queryKey, queryFunction, options)
}
2022-12-10 20:19:18 +01:00
type MutationVarsAnnouncement = { tag: string; to: boolean }
const mutationFunction = async ({ tag, to }: MutationVarsAnnouncement) => {
return apiInstance<{}>({
method: 'post',
url: `tags/${tag}/${to ? 'follow' : 'unfollow'}`
})
2022-11-20 16:14:08 +01:00
}
const useTagsMutation = (options: UseMutationOptions<{}, AxiosError, MutationVarsAnnouncement>) => {
return useMutation(mutationFunction, options)
}
export { useFollowedTagsQuery, useTagsQuery, useTagsMutation }