2

I am working on adding an express router for something like profile address. The profile address is a unique name comes after the main URL. For instance: www.domain.com/superCat But the problem is, this route will destroy all other routes.

Here is what I have done:

router.get('/:profileAddress', userController.profileAddress);
router.param("profileAddress", async (req, res, next, val) => {

  // check the parameter if exists in the database
  const account = await Account.findOne({
    where: {profileAddress: val}
  });

  try {

    if(account && account !== ""){

      // render the user profile
      const accountId = account.accountId;
      const userData = await Account.findOne({ where: { accountId: accountId } });
      const results = await Calenders.findAll({ where: { accountId: accountId } });
      const avatar = await Avatars.findOne({ where: { accountId: accountId } });

      return res.render("user/userProfile", {
        title: "User Profile",
        data: results,
        userData: userData,
        avatar: avatar,
      });

    }else{
      console.log("Yes it works");
      // if not exists in the database, go to next process
      return next();

    }
    
  } catch (error) {
    console.log(" ********** Error ", error)
  }

});

// inside the controller
exports.profileAddress = async (req, res, next) => {
  console.log("Yes it works, controller");
  next();
}

But it will go to not found route, if the parameter not found in the database.

But I do not want something like adding more specific router, because it is the client requirements. I am looking for any solution like if I can add a middleware or regex.

Mahdi
  • 206
  • 2
  • 14

0 Answers0