roomActions.js 4.33 KB
import axios from "axios";
import qs from "qs";
import {
  ROOM_CHECK_AVAILABILITY_REQUEST,
  ROOM_CHECK_AVAILABILITY_SUCCESS,
  ROOM_CHECK_AVAILABILITY_RESET,
  ROOM_CHECK_AVAILABILITY_FAIL,
  ROOM_MAKE_REVIEW_REQUEST,
  ROOM_MAKE_REVIEW_SUCCESS,
  ROOM_MAKE_REVIEW_RESET,
  ROOM_MAKE_REVIEW_FAIL,
  ROOM_FETCH_BOOKED_DATES_SUCCESS,
  ROOM_FETCH_BOOKED_DATES_FAIL,
  ALL_ROOMS_FAIL,
  ALL_ROOMS_SUCCESS,
  ROOM_DETAILS_SUCCESS,
  ROOM_DETAILS_FAIL,
  CLEAR_ERRORS
} from "../constants/roomConstants";
import { getSession } from "next-auth/react";

// Get all rooms
export const getRooms =
  (currentPage = 1, location = "", guests, category) =>
  async dispatch => {
    try {
      const roomsPerPage = 4;
      const query = {
        filters: {
          address: {
            $contains: location
          }
        },
        populate: ["images"],
        pagination: {
          pageSize: roomsPerPage,
          page: currentPage
        }
        // sort: ['title:asc'],
        // fields: ['title'],
        // publicationState: 'live',
        // locale: ['en'],
      };

      // Add all the optional filters.
      if (guests) query.filters["guestCapacity"] = { $eq: guests };
      if (category) query.filters["category"] = { $eq: category };

      const queryString = qs.stringify(query, {
        encodeValuesOnly: true // prettify URL
      });

      const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/rooms?${queryString}`);

      dispatch({
        type: ALL_ROOMS_SUCCESS,
        payload: response.data
      });
    } catch (error) {
      console.log("Real error is: ");
      console.log(error);

      dispatch({
        type: ALL_ROOMS_FAIL,
        payload: error.response.data
      });
    }
  };

// Get room details
export const getRoomDetails = roomId => async dispatch => {
  try {
    const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/rooms/${roomId}?populate[0]=images`);

    dispatch({
      type: ROOM_DETAILS_SUCCESS,
      payload: response.data
    });
  } catch (error) {
    dispatch({
      type: ROOM_DETAILS_FAIL,
      payload: error.response.data
    });
  }
};

// Check for room availability
export const checkRoomAvailability = (roomId, checkInDate, checkOutDate) => async dispatch => {
  try {
    dispatch({
      type: ROOM_CHECK_AVAILABILITY_REQUEST
    });

    const response = await axios.get(
      `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/rooms/check-availability?roomId=${roomId}&checkInDate=${checkInDate}&checkOutDate=${checkOutDate}`
    );

    dispatch({
      type: ROOM_CHECK_AVAILABILITY_SUCCESS,
      payload: response.data
    });
  } catch (error) {
    // console.log("Error while check room availability");
    // console.log(error);
    dispatch({
      type: ROOM_CHECK_AVAILABILITY_FAIL,
      payload: error.response.data
    });
  }
};

// Fetch room booked dates.
export const fetchRoomBookedDates = roomId => async dispatch => {
  try {
    const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/rooms/fetch-booked-dates?roomId=${roomId}`);

    dispatch({
      type: ROOM_FETCH_BOOKED_DATES_SUCCESS,
      payload: response.data
    });
  } catch (error) {
    dispatch({
      type: ROOM_FETCH_BOOKED_DATES_FAIL,
      payload: error.response.data
    });
  }
};

// update profile.
export const makeReview = reviewData => async dispatch => {
  const session = await getSession();
  if (!session) {
    throw new Error("You need to be logged in before creating a review.");
  }

  try {
    dispatch({
      type: ROOM_MAKE_REVIEW_REQUEST
    });

    const config = {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${session.jwt}`
      }
    };

    const response = await axios.post(
      `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/rooms/reviews`,
      {
        rating: reviewData.rating,
        comment: reviewData.comment,
        roomId: reviewData.roomId
      },
      config
    );

    dispatch({
      type: ROOM_MAKE_REVIEW_SUCCESS,
      payload: response.data
    });
  } catch (error) {
    console.log("Error while making a review: ");
    console.log(error);

    dispatch({
      type: ROOM_MAKE_REVIEW_FAIL,
      payload: error.response.data
    });
  }
};

// Clear errors
export const clearErrors = () => async dispatch => {
  dispatch({
    type: CLEAR_ERRORS
  });
};