tooot/src/utils/queryHooks/relationship.ts

87 lines
2.0 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-01-11 21:36:57 +01:00
import {
2021-12-18 19:59:38 +01:00
QueryFunctionContext,
2021-01-11 21:36:57 +01:00
useMutation,
UseMutationOptions,
useQuery,
UseQueryOptions
} from 'react-query'
2021-01-07 19:13:09 +01:00
2021-01-10 02:12:14 +01:00
export type QueryKeyRelationship = [
'Relationship',
{ id: Mastodon.Account['id'] }
]
2021-01-07 19:13:09 +01:00
2021-12-18 19:59:38 +01:00
const queryFunction = ({
queryKey
}: QueryFunctionContext<QueryKeyRelationship>) => {
2021-01-07 19:13:09 +01:00
const { id } = queryKey[1]
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Relationship[]>({
2021-01-07 19:13:09 +01:00
method: 'get',
url: `accounts/relationships`,
params: {
'id[]': id
}
2021-02-11 01:33:31 +01:00
}).then(res => res.body)
2021-01-07 19:13:09 +01:00
}
2021-01-11 21:36:57 +01:00
const useRelationshipQuery = ({
2021-01-07 19:13:09 +01:00
options,
...queryKeyParams
2021-01-10 02:12:14 +01:00
}: QueryKeyRelationship[1] & {
options?: UseQueryOptions<
Mastodon.Relationship[],
AxiosError,
Mastodon.Relationship
>
2021-01-07 19:13:09 +01:00
}) => {
2021-01-10 02:12:14 +01:00
const queryKey: QueryKeyRelationship = ['Relationship', { ...queryKeyParams }]
return useQuery(queryKey, queryFunction, {
...options,
select: data => data[0]
})
2021-01-07 19:13:09 +01:00
}
2021-01-11 21:36:57 +01:00
type MutationVarsRelationship =
| {
id: Mastodon.Account['id']
type: 'incoming'
payload: { action: 'authorize' | 'reject' }
}
| {
id: Mastodon.Account['id']
type: 'outgoing'
payload: { action: 'follow' | 'block'; state: boolean }
}
const mutationFunction = async (params: MutationVarsRelationship) => {
switch (params.type) {
case 'incoming':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Relationship>({
2021-01-11 21:36:57 +01:00
method: 'post',
url: `follow_requests/${params.id}/${params.payload.action}`
2021-02-11 01:33:31 +01:00
}).then(res => res.body)
2021-01-11 21:36:57 +01:00
case 'outgoing':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Relationship>({
2021-01-11 21:36:57 +01:00
method: 'post',
url: `accounts/${params.id}/${params.payload.state ? 'un' : ''}${
params.payload.action
}`
2021-02-11 01:33:31 +01:00
}).then(res => res.body)
2021-01-11 21:36:57 +01:00
}
}
const useRelationshipMutation = (
options: UseMutationOptions<
Mastodon.Relationship,
AxiosError,
MutationVarsRelationship
>
) => {
return useMutation(mutationFunction, options)
}
export { useRelationshipQuery, useRelationshipMutation }