smackeem / SkyLoom-Project-3

0 stars 0 forks source link

Grow Backend: Creating DRY code #1

Open smackeem opened 10 months ago

smackeem commented 10 months ago

When communicating with the API, the url is created by appending the key value pairs to the base URL and sending a GET request as well as an Access token. The difference between getting a OneWay Ticket and a Round trip is adding a return date to the URL. So to improve this I would have the one route service both requests with a helper function to filter out the body and add to base URL. Otherwise, my backend is pretty solid.

This is the same request for getRoundWayTrip so I would want to make it just one but if a returnDate property exists, then append it to URL otherwise don't.

async function getOneWayTrip(req, res, next) {
  try {
    console.log(req.token);
    const {
      originLocationCode,
      destinationLocationCode,
      departureDate,
      adults,
      max,
    } = req.body;
    console.log(req.body);
    const url = `https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=${originLocationCode}&destinationLocationCode=${destinationLocationCode}&departureDate=${departureDate}&adults=${adults}&max=${max}`;
    const response = await fetch(url, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${req.token}`,
        "Content-Type": "application/json",
      },
    });
    if (response.ok) {
      return res.status(200).json(await response.json());
    } else {
      const errorBody = await response.text();
      console.error("Error Response:", errorBody);
      return res
        .status(response.status)
        .json({ error: "Failed to fetch flight offers." });
    }
  } catch (err) {
    res.status(400).json({ err: err.message });
  }
}
SamPatt commented 10 months ago

Creating DRY code

While keeping things DRY is important I'd say if you're only dealing with two functions, it may not be worth refactoring it into a single function. But you've already identified how it could be done, and if you did take the time, then your approach makes sense to me.

This code block looks good to me, it has error handling built in and it's understandable.

Overall server areas for improvement

I couldn't find very much to improve upon: