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

How do you create middleware for a specific route and method? #207

Closed
OultimoCoder opened this issue May 9, 2022 · 3 comments
Closed

How do you create middleware for a specific route and method? #207

OultimoCoder opened this issue May 9, 2022 · 3 comments

Comments

@OultimoCoder
Copy link

Say I wanted to validate the parameters for a post request using middleware but not affect the other methods like get etc, I would like to be able to do:

const route = app.route('/users')
route.post('/', validate(userValidation.createUser), userController.createUser)

But that isn't possible, the only way I can see to do it currently is:

const route = app.route('/users')
app.user('/users', validate(userValidation.createUser))
route.post('/', userController.createUser)

But this does it for all methods in the /users route, I could check in the middleware for the route method but this isn't ideal. Is there a way to do this that I am missing?

@yusukebe
Copy link
Member

yusukebe commented May 9, 2022

Hi @OultimoCoder

We were just talking about it! #189

If this comes true, we can write this way.

const route = app.route('/users')
route.post('/', validate(userValidation.createUser), userController.createUser)

We are planning to release the Hono including this feature. Maybe it's v1.2.0.

Before it is released, you can write like this:

const mid = async (c: Context, next) => {
  await next()
  c.header('x-custom', 'abc')
}

app.use('*', async (c, next) => {
  if (c.req.method === 'GET') {
    await mid(c, next)
  } else {
    await next()
  }
})

app.get('/', (c) => {
  return c.text('Hello')
})

Thank you!

@OultimoCoder
Copy link
Author

OultimoCoder commented May 9, 2022 via email

@yusukebe
Copy link
Member

Hi @OultimoCoder

We released v1.2.0 including new features.
https://github.com/honojs/hono/releases/tag/v1.2.0

You can write like this:

import { Hono, Route } from 'hono'

const app = new Hono()
const route = new Route()

route.post('/', validate(userValidation.createUser), userController.createUser)
app.route('/users', route)

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