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

85.71% Statements 12/14
50% Branches 1/2
83.33% Functions 5/6
85.71% Lines 12/14

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 75 76                1x                                         1x                 2x   2x   2x   1x 1x           1x 1x         1x 1x               1x                  
import { useMutation, useQueryClient } from '@tanstack/react-query';
 
import { QUERY_KEYS, RequestFor } from '@repo/hooks/userQueries';
 
import { REQUEST_POLICY, runRequestEffect } from '@repo/services/effectRequest';
 
import { useReallocationV2Runtime } from '../screens/ReallocationV2/runtime';
 
const ENDPOINTS = {
  LIST_REQUESTS: '/api/tickets',
};
 
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 },
    },
  } = useReallocationV2Runtime();
 
  const queryClient = useQueryClient();
 
  return useMutation({
    mutationFn: (payload: ReallocationRequestPayload) => {
      return runRequestEffect(async () => {
        Iif (!baseApiUrl) {
          throw new Error(
            'baseApiUrl is required to submit reallocation request',
          );
        }
 
        await requestWithAuthGuard(() =>
          mainHttp.post(ENDPOINTS.LIST_REQUESTS, payload),
        );
      }, REQUEST_POLICY.WRITE);
    },
    onSuccess: (_, payload) => {
      onSuccess?.(payload);
      queryClient.invalidateQueries({
        queryKey: [
          QUERY_KEYS.MY_REQUESTS,
          RequestFor.ME,
          'reallocation',
          'all',
        ],
      });
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.ME],
      });
    },
    onError: error => {
      onError?.(error);
    },
  });
};