Home > database >  NodeJS: best practice get result of sample url for users and admins
NodeJS: best practice get result of sample url for users and admins

Time:11-22

This is my url:

/coins/list

If users fetch url, we show this result:

{
  'title': 'hello'
}

And if admins fetch url, we show this result:

{
  'title': 'hello',
  'id': '1',
  'date': '2020-01-01'
}

Now, I write this code in my controller:

const coinsList = async (req: Request, res: Response, next: NextFunction) => {
  if (req.isAdmin) {
    return coinsService.showAdminData()
  } else {
    return coinsService.showUserData()
  }
}

Is that true?

What is the best way for handle it?

CodePudding user response:

You Can surely do this . But instead of calling separate method for sending response we can do the following:

const coinsList = async (req: Request, res: Response, next: NextFunction) => {
  const allData = coinsService.getAllData(); 
  if (req.isAdmin) {
   return allData; 
  } else {
   const dataForUsers = { title: allData.title } 
   return dataForUsers; 
  }
}

Ok so what is the benifit by doing this . Well in this way you can centralize all the day in one place and don't need to worry about separate user access policy and you will need to call method only once and leter on you can manipulate or do your stuffs with that data without calling the method again and again . Hopefully this will reduce your time and space complexity . But again different apps have different usecases so depending on need the above model can be modified also .

  • Related