Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
getBioEntity.ts 1.79 KiB
import { bioEntityResponseSchema } from '@/models/bioEntityResponseSchema';
import { apiPath } from '@/redux/apiPath';
import { axiosInstanceNewAPI } from '@/services/api/utils/axiosInstance';
import { BioEntityContent, BioEntityResponse } from '@/types/models';
import { PerfectSearchParams } from '@/types/search';
import { ThunkConfig } from '@/types/store';
import { getErrorMessage } from '@/utils/getErrorMessage';
import { validateDataUsingZodSchema } from '@/utils/validateDataUsingZodSchema';
import { createAsyncThunk } from '@reduxjs/toolkit';
import { addNumbersToEntityNumberData } from '../../entityNumber/entityNumber.slice';
import { BIO_ENTITY_FETCHING_ERROR_PREFIX } from '../bioEntity.constants';

type GetBioEntityProps = PerfectSearchParams;

export const getBioEntity = createAsyncThunk<
  BioEntityContent[] | undefined,
  GetBioEntityProps,
  ThunkConfig
>(
  'project/getBioEntityContents',
  async (
    { searchQuery, isPerfectMatch, addNumbersToEntityNumber = true },
    { rejectWithValue, dispatch },
  ) => {
    try {
      const response = await axiosInstanceNewAPI.get<BioEntityResponse>(
        apiPath.getBioEntityContentsStringWithQuery({ searchQuery, isPerfectMatch }),
      );

      const isDataValidBioEnity = validateDataUsingZodSchema(
        response.data,
        bioEntityResponseSchema,
      );

      if (addNumbersToEntityNumber && response.data.content) {
        const bioEntityIds = response.data.content.map(b => b.bioEntity.elementId);
        dispatch(addNumbersToEntityNumberData(bioEntityIds));
      }

      return isDataValidBioEnity ? response.data.content : undefined;
    } catch (error) {
      const errorMessage = getErrorMessage({
        error,
        prefix: BIO_ENTITY_FETCHING_ERROR_PREFIX,
      });
      return rejectWithValue(errorMessage);
    }
  },
);