All files / apps/reallocation/src/hooks useRequest.ts

100% Statements 13/13
100% Branches 2/2
100% Functions 6/6
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                                                      1x                 4x   4x   4x   2x 2x 1x         1x 1x         1x 1x               1x         1x        
import { useMutation, useQueryClient } from '@tanstack/react-query';
 
import { API_ENDPOINTS } from '@repo/constants/endpoints';
 
import { RequestFor, USER_QUERY_KEYS } from '@repo/hooks/useUserQueries';
 
import { REQUEST_POLICY, runRequestEffect } from '@repo/services/effectRequest';
 
import { useReallocationRuntime } from '../screens/Reallocation/runtime';
 
export interface ReallocationRequestPayload {
  cc: string[];
  category: string;
  data: {
    origin: string;
    dest: string;
    time: string;
    note: string;
  };
  mealConfig: {
    lunch: boolean;
    breakfast: boolean;
    vegetarian: boolean;
    office: string;
  };
}
 
export const useCreateReallocationRequest = (
  onSuccess?: (payload?: ReallocationRequestPayload) => void,
  onError?: (error: unknown) => void,
) => {
  const {
    state: { baseApiUrl },
    meta: {
      api: { mainHttp, requestWithAuthGuard },
    },
  } = useReallocationRuntime();
 
  const queryClient = useQueryClient();
 
  return useMutation({
    mutationFn: (payload: ReallocationRequestPayload) => {
      return runRequestEffect(async signal => {
        if (!baseApiUrl) {
          throw new Error(
            'baseApiUrl is required to submit reallocation request',
          );
        }
 
        await requestWithAuthGuard(() =>
          mainHttp.post(API_ENDPOINTS.LIST_REQUESTS, payload, { signal }),
        );
      }, REQUEST_POLICY.WRITE);
    },
    onSuccess: (_, payload) => {
      onSuccess?.(payload);
      queryClient.invalidateQueries({
        queryKey: [
          USER_QUERY_KEYS.MY_REQUESTS,
          RequestFor.ME,
          'reallocation',
          'all',
        ],
      });
      queryClient.invalidateQueries({
        queryKey: [USER_QUERY_KEYS.ME],
      });
    },
    onError: error => {
      onError?.(error);
    },
  });
};