Home > Mobile >  get rid of duplicate routes
get rid of duplicate routes

Time:03-03

I'm creating a website using express and node.js. I've 2 routes here like /recipe and '/recipe/:item'. here my item is an ingredient like chicken or onions.

Both of these routes generate a list of items in return. and here is my sample code.

router.get("/recipeList/:ingredient", async (req, res) => {
  let entityId = req.params.ingredient;
  try {
    const resp = await axios.get(
      `myApi&filter={ 'c_ingredients':{ '$contains':"${entityId}"}}`
    );

    res.render("/recipeList", {
      data: resp.data.response,
     });
  } catch (err) {
    console.log(err);
  }
});

router.get("/recipeList", async (req, res) => {
  let entityId = req.params.ingredient;
  try {
    const resp = await axios.get(
      `myApi`
    );
     res.render("recipeList", {
      data: resp.data.response.entities,
    });
  } catch (err) {
    console.log(err);
  }
});

I see that the code in both the blocks is the same (apart from the API endpoint, which I can handle in a simple conditional variable). How can I get rid of this duplicate code and have a single block to handle both conditions?

CodePudding user response:

I am trusting you if both methods were the same, if It doesnt work tellme

const endPoint = async (req, res) => {
  let entityId = req.params.ingredient;
  try {
    const resp = await axios.get(
      `myApi`
    );
     res.render("recipeList", {
      data: resp.data.response.entities,
    });
  } catch (err) {
    console.log(err);
  }
};

router.get("/recipeList/:ingredient", endPoint);

router.get("/recipeList",endPoint);

CodePudding user response:

You can use a question mark in the router parameter to tell express its optional.

Do something like this:

router.get("/recipeList/:ingredient?", async (req, res) => {

    let URI = `myApi`;

    if(req.params.ingredient){
        URI = `myApi&filter={ 'c_ingredients':{ '$contains':"${entityId}"}}`;
    }

    try{

        let resp = await axios.get(URI);

        res.render("recipeList", {
            data: (req.params.ingredient ? resp.data.response : resp.data.response.entities)
        });

    }catch(err){

        res.status(500).end();

    }  
  
  });

If no ingredient parameter is passed, its use the default url. If you set on, it perform your more "complex" http request.

Note that i have not tested the code and i can possible contain little errors/mistakes.

  • Related