import { QueryFunctionContext, useMutation, UseMutationOptions, useQuery, UseQueryOptions } from '@tanstack/react-query' import apiInstance from '@utils/api/instance' import { AxiosError } from 'axios' export type QueryKeyRelationship = ['Relationship', { id?: Mastodon.Account['id'] }] const queryFunction = async ({ queryKey }: QueryFunctionContext) => { const { id } = queryKey[1] if (!id) return Promise.reject() const res = await apiInstance({ method: 'get', url: `accounts/relationships`, params: { 'id[]': id } }) return res.body } const useRelationshipQuery = ({ options, ...queryKeyParams }: QueryKeyRelationship[1] & { options?: UseQueryOptions }) => { const queryKey: QueryKeyRelationship = ['Relationship', { ...queryKeyParams }] return useQuery(queryKey, queryFunction, { ...options, enabled: (typeof options?.enabled === 'boolean' ? options.enabled : true) && !!queryKeyParams.id, select: data => data[0] }) } type MutationVarsRelationship = | { id: Mastodon.Account['id'] type: 'incoming' payload: { action: 'authorize' | 'reject' } } | { id: Mastodon.Account['id'] type: 'outgoing' payload: { action: 'block' state: boolean reblogs?: undefined notify?: undefined } } | { id: Mastodon.Account['id'] type: 'outgoing' payload: { action: 'follow' state: boolean reblogs?: boolean notify?: boolean } } const mutationFunction = async (params: MutationVarsRelationship) => { switch (params.type) { case 'incoming': return apiInstance({ method: 'post', url: `follow_requests/${params.id}/${params.payload.action}` }).then(res => res.body) case 'outgoing': const formData = new FormData() typeof params.payload.reblogs === 'boolean' && formData.append('reblogs', params.payload.reblogs.toString()) typeof params.payload.notify === 'boolean' && formData.append('notify', params.payload.notify.toString()) return apiInstance({ method: 'post', url: `accounts/${params.id}/${params.payload.state ? 'un' : ''}${params.payload.action}`, body: formData }).then(res => res.body) } } const useRelationshipMutation = ( options: UseMutationOptions ) => { return useMutation(mutationFunction, options) } export { useRelationshipQuery, useRelationshipMutation }