ndelvalle/generator-api

How to chain middleware in routes.

syz3r opened this issue · 3 comments

syz3r commented

Hi,

Thanks for creating this amazing project. I'm new to es6 and need some help router file.
I use chain auth middleware in routes like this before.
router.get('/', auth.hasRole('admin'), controller.find)

Using above code results in following error.
Cannot read property 'facade' of undefined

Could please explain how can i chain middleware with new syntax.
router.route('/test').get((...args) => controller.test(...args));

Also if you can explain facade pattern in readme file with example it will really helpfull

syz3r commented

Got it working. Closing this.

router.route('/')
  .get(auth.hasRole('admin'), (...args) => { controller.find(...args) })
  .post(auth.hasRole('admin'), (...args) => controller.create(...args));

@syz3r thanks for reaching out and for posting the solution 😄

I think you have to pass an arrow function instead of directly the method to keep the this context.

If you want to set a middleware for all the handlers you can do this:

router.use(auth.hasRole('admin'));

router.route('/')
  .get((...args) => controller.find(...args))
  .post((...args) => controller.create(...args));

Just keep in mind that every following route that you defined will use that middleware.

Also if you can explain facade pattern in readme file with example it will really helpful

Yes, indeed! I just opened an issue for it #39, also if you want and can help with that just open a PR.

@syz3r the facade pattern is designed to be a wrapper around mongoose, so all things related to the DB like populating, querying, sorting mongoose docs should be here, note that you can reference other models from each model of necessary.