2

I couldn't find an answer in the docs, and I'm hoping there's a way to do what I need. I have some express routes:

app.post( '/submit-agency-event'            , eventService.submitEvent );
app.post( '/submit-question'                , formService.submitQuestion );
app.post( '/submit-information-request'     , formService.submitInformationRequest );
app.post( '/social-worker-register-family'  , familyService.registerFamily );

where each route uses a function in a middleware file to process the request. I'd like to restrict one route to only a few userTypes (which is stored on req.user.userType). I'd like to set up the route similar to the following:

app.post( '/social-worker-register-child'   , middleware.requireUsersOfType( ['admin, social worker'] ), childService.registerChild );

then use the function requireUsersOfType() to handle processing and any needed redirects before childService.registerChild() is called.

exports.requireUsersOfType = ( req, res, next, userTypesArray ) => {
    // processing
};

What I can't seem to figure out is how to pass parameters into the requireUsersOfType() function. Does anyone know how this can be done?

autoboxer
  • 1,358
  • 1
  • 16
  • 37

2 Answers2

0

You can use Closures:

A closure is the combination of a function and the lexical environment within which that function was declared.

Example:

exports.requireUsersOfType = (userTypesArray) => {
  return function(req, res, next) => {
    // your code...
  } 
};
0

While not the most elegant solution, if you can't get it working as others have suggested, this should do the trick:

app.post( '/social-worker-register-child', function( req, res, next ) { middleware.requireUsersOfType( req, res, next, userTypes = ['admin, social worker'] ); }, childService.registerChild );

You should then be able to do your processing in middleware as desired:

exports.requireUsersOfType = ( req, res, next, userTypesArray ) => {
    // processing
};
n-devr
  • 450
  • 1
  • 3
  • 10