Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

importing the request in expressjs

I’m creating a helper method in my code which I can use for authorizing users,

I am creating a function called "usePermissions" following the react way but on the back-end.

The usePermissions() will return true or false based on some x, y and z.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But this method depends on the request object,

so in order to make it work, I’ll everywhere have to call
usePermissions(req),
ex:

import usePermissions from 'hooks/usePermissions'

usersRouter.delete('/users/:userId', async (req, res, next)=>{
  const { verify } = usePermissions(req)
  if(verify('deleteUsers')) await UserModel.delete(req.params.userId)
  // ...
})

Is there a way to package this "usePermissions" helper method with the request object?

I want it to automatically have the request object, I don’t want to keep passing it as a variable,

how to make it have the request object without having to pass it as an argument to it, is it possible?

ex:

import usePermissions from 'hooks/usePermissions'

usersRouter.delete('/users/:userId', async (req, res, next)=>{
  const { verify } = usePermissions() // <-- see, I want to not pass the req object
  if(verify('deleteUsers')) await UserModel.delete(req.params.userId)
  // ...
})

>Solution :

You can create a middleware that will call usePermissions and append result to the Request object, so it will become available in all your handlers without explicitly calling it.

Your middleware code might look something like (read more about using middlewares in Express app)

export function getUsePermissions = (req, res, next) => {
  const { verify } = usePermissions(req);
  req['verify'] = verify

  // moving to the next middleware in chain, now Request object has a verify property
  return next()
}

and in your express app, add getUsePermissions middleware

express.use(getUsePermissions);

now you can use extract usePermissions from request object in your handlers:

usersRouter.delete('/users/:userId', async (req, res, next)=>{
  const { verify } = req['verify'];
  if(verify('deleteUsers')) await UserModel.delete(req.params.userId)
  // ...
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading