bookingActions.js 2.72 KB
import axios from "axios";
import { BOOKING_DETAILS_SUCCESS, BOOKING_DETAILS_FAIL, FETCH_MY_BOOKINGS_SUCCESS, FETCH_MY_BOOKINGS_FAIL, CLEAR_ERRORS } from "../constants/bookingConstants";
import qs from "qs";

// Fetch room booked dates.
export const fetchMyBookings = session => async dispatch => {
  // Note, when an action is going to be triggered on the server side, like this one is.
  // then we cannot expect getSession() to give usa  valid session, we need to instead use getSession({ req })
  // and give it a req object instead.
  // This action gets called from getServerSideProps on the me.js file.
  // Hence here we have taken the session object from outside, instead of using getSession().
  // Unlike a few other actions where we might have ended up using getSession directly, those actions like the loadUser & updateUser actions
  // are all triggered on the UI using useEffect and from a submitHandler respectively.
  if (!session) {
    throw new Error("You are not authenticated currently. Only authenticated users can fetch their own bookings.");
  }

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

    const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/my-bookings`, config);

    dispatch({
      type: FETCH_MY_BOOKINGS_SUCCESS,
      payload: response.data.bookings
    });
  } catch (error) {
    dispatch({
      type: FETCH_MY_BOOKINGS_FAIL,
      payload: error.response.data
    });
  }
};

// Get room details
export const getBookingDetails = (bookingId, session) => async dispatch => {
  // const session = await getSession();
  if (!session) {
    throw new Error("You are not authenticated currently. Only authenticated users can fetch their own bookings.");
  }

  try {
    const config = {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${session.jwt}`
      }
    };
    const query = qs.stringify(
      {
        populate: {
          room: {
            populate: ["images"]
          },
          user: {
            populate: ["*"]
          }
        }
      },
      {
        encodeValuesOnly: true // prettify URL
      }
    );

    const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/bookings/${bookingId}?${query}`, config);

    dispatch({
      type: BOOKING_DETAILS_SUCCESS,
      payload: response.data
    });
  } catch (error) {
    console.log("getBookingDetails:");
    console.log(error.response.data);

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

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