diff --git a/src/frontend/apps/desk/src/features/teams/api/index.ts b/src/frontend/apps/desk/src/features/teams/api/index.ts index 5b969f5..a5dd14a 100644 --- a/src/frontend/apps/desk/src/features/teams/api/index.ts +++ b/src/frontend/apps/desk/src/features/teams/api/index.ts @@ -3,3 +3,4 @@ export * from './useCreateTeam'; export * from './useTeam'; export * from './useTeams'; export * from './useTeamsAccesses'; +export * from './useUpdateTeamAccess'; diff --git a/src/frontend/apps/desk/src/features/teams/api/useUpdateTeamAccess.ts b/src/frontend/apps/desk/src/features/teams/api/useUpdateTeamAccess.ts new file mode 100644 index 0000000..826ccf3 --- /dev/null +++ b/src/frontend/apps/desk/src/features/teams/api/useUpdateTeamAccess.ts @@ -0,0 +1,68 @@ +import { + UseMutationOptions, + useMutation, + useQueryClient, +} from '@tanstack/react-query'; + +import { APIError, errorCauses, fetchAPI } from '@/api'; + +import { Access, Role } from './types'; +import { KEY_TEAM } from './useTeam'; +import { KEY_LIST_TEAM_ACCESSES } from './useTeamsAccesses'; + +interface UpdateTeamAccessProps { + teamId: string; + accessId: string; + role: Role; +} + +export const updateTeamAccess = async ({ + teamId, + accessId, + role, +}: UpdateTeamAccessProps): Promise => { + const response = await fetchAPI(`teams/${teamId}/accesses/${accessId}/`, { + method: 'PATCH', + body: JSON.stringify({ + role, + }), + }); + + if (!response.ok) { + throw new APIError('Failed to update role', await errorCauses(response)); + } + + return response.json() as Promise; +}; + +type UseUpdateTeamAccess = Partial; + +type UseUpdateTeamAccessOptions = UseMutationOptions< + Access, + APIError, + UseUpdateTeamAccess +>; + +export const useUpdateTeamAccess = (options?: UseUpdateTeamAccessOptions) => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: updateTeamAccess, + ...options, + onSuccess: (data, variables, context) => { + void queryClient.invalidateQueries({ + queryKey: [KEY_LIST_TEAM_ACCESSES], + }); + void queryClient.invalidateQueries({ + queryKey: [KEY_TEAM], + }); + if (options?.onSuccess) { + options.onSuccess(data, variables, context); + } + }, + onError: (error, variables, context) => { + if (options?.onError) { + options.onError(error, variables, context); + } + }, + }); +};