Search code examples
javascriptnode.jsexpressnode-mysql2

NODEJS: The Response returned by the API is empty when the actual object is not


I have a handler to handle a specific route in nodejs with express.

async function handleGetAllBookingByUserId(req, res, next) {
  try {
    let bookings = await pool.execute(queries.getAllBookingByUserId, [
      req.params.userId,
    ]);
    let map_ = await groupByBookings(bookings);
    console.log(map_.values());
    res.send(map_.values());
  } catch (err) {
    next(err);
  }
}

The function groupByBookings:

async function groupByBookings(bookings) {
  let map_ = new Map();
  for (let i = 0; i < (await bookings[0].length); i++) {
    let current = await bookings[0][i];
    let {
      bookingid,
      venueid,
      userid,
      bookingtimestamp,
      bookingstatus,
      paymenttype,
      price,
      timeslotstart,
      timeslotend,
      noofcourts,
    } = current;
    if (map_.has(current.id)) {
      map_.get(current.id).slots.push({ timeslotstart, timeslotend });
    } else {
      newObj = {
        bookingid,
        venueid,
        userid,
        bookingtimestamp,
        bookingstatus,
        paymenttype,
        price,
        noofcourts,
      };
      newObj.slots = [];
      newObj.slots.push({ timeslotstart, timeslotend });
      map_.set(bookingid, newObj);
    }
  }
  return map_;
}

When i console log i get the output but somehow , the Response is an empty object. I presume im doing something wrong with the async logic which im not sure of. Any help?


Solution

  • i was able to get the response as the Map.values() is an iterable.

    I had to pass the result as

    [...map_.values()]
    

    so something like

    res.send([...map_.values()])