Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to use function inside handler. #40

Open
ppot opened this issue Mar 8, 2018 · 1 comment
Open

Ability to use function inside handler. #40

ppot opened this issue Mar 8, 2018 · 1 comment

Comments

@ppot
Copy link

ppot commented Mar 8, 2018

For auth purpose It would be good to be able to pass function to our handler.

This way you can use: get('/account', auth(account)) instead of

module.exports = async (req, res) => {
   await auth(req)
 }
@armand1m
Copy link

armand1m commented Jun 2, 2018

You can create a Higher Order Function for that.

const { send } = require('micro')
const { router, get } = require('microrouter')
const auth = require('../auth-from-somewhere');

const withAuth = (route) => 
  async (req, res) => {
    try {
      await auth(req);
      return route(req, res);
    } catch(e) {
      send(res, 401, 'Ńot allowed');
    }
  };

const hello = (req, res) => send(res, 200, `Hello ${req.params.who}`)
const notfound = (req, res) => send(res, 404, 'Not found route')

module.exports = router(
  get('/hello/:who', withAuth(hello)), 
  get('/*', notfound)
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants