assignment/get-api

PHOTO EMBED

Mon Oct 17 2022 17:42:27 GMT+0000 (Coordinated Universal Time)

Saved by @j_jivan #javascript

// assignment/get-api

// Problem 1 Create an API for GET /movies that returns a list of movies. Define an array of movies in your code and return the value in response.
const movies = [
  "Top Gun: Maverick",
  "Doctor Strange in the Multiverse of Madness",
  "Jurassic World Dominion",
  "The Batman",
  "Minions: The Rise of Gru",
  "Thor: Love and Thunder",
  "Sonic the Hedgehog 2",
  "Elvis",
  "Uncharted Sony",
];
const color = [
  "#fcba03",
  "#62fc03",
  "#03fce3",
  "#035efc",
  "#8003fc",
  "#f403fc",
  "#fc034e",
  "#03fc3d",
  "#fceb03",
];
router.get("/movies", (req, res) => {
  res.write(`<div style="color:blue;text-align:center;" >`);
  movies.forEach((each, i) => {
    res.write(`<h1 style="color:${color[i]};" >${each}<h1/>`);
  });
  res.write(`<div/>`);
  res.end();
});

//Problem=2 Create an API GET /movies/:indexNumber (For example GET /movies/1 is a valid request and it should return the movie in your array at index 1). You can define an array of movies again in your api

router.get("/movies/:ind", (req, res) => {
  const i = Number(req.params.ind);
  if (i < movies.length && typeof i === "number") {
    res.write(`<h1 style="color:${color[i]};" >${movies[i]}<h1/>`);
  } else {
    res.send("Not a valid request");
  }
});

//Problem 4== Write another api called GET /films. Instead of an array of strings define an array of movie objects this time. Each movie object should have values - id, name.

const filemsArr = [];
for (let i = 0; i < movies.length; ++i) {
  filemsArr.push({
    id: i + 1,
    Movie: movies[i],
    Color: color[i],
  });
} 

router.get("/films", (req, res) => {
  res.write(`<div style="color:blue;text-align:center;" >`);
  filemsArr.forEach((each) => {
    res.write(
      `<h1 style="color:${each.Color};" >${each.id}--> ${each.Movie}<h1/>`
    );
  });
  res.write(`<div/>`);
  res.end();
});

//Problem 5 == Write api GET /films/:filmId where filmId is the value received in request path params. Use this value to return a movie object with this id. In case there is no such movie present in the array, return a suitable message in the response body.

router.get("/films/:id", (req, res) => {
  const i = Number(req.params.id);
  if (i < movies.length && typeof i === "number") {
    res.write(
      `<h1 style="color:${filemsArr[i].Color};" > id: ${filemsArr[i].id} ==> ${filemsArr[i].Movie}<h1/>`
    );
  } else {
    res.send("No movie exists with this id");
  }
});
content_copyCOPY