How can I implement the Custom Methods approach with Hono? #4380
-
|
Given that Hono uses colons to indicate path segments as params (ie. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
|
1. Use Literal ✅ Works because 2. Alternative: Catch-All Param and Parse ✅ This is more flexible if you have many actions per resource. 3. Notes / Best Practices
💡 TL;DR:
|
Beta Was this translation helpful? Give feedback.
-
This is not true |
Beta Was this translation helpful? Give feedback.
-
|
The earlier Use an explicit regexp on the parameter instead: app.post('/users/:id{[^:]+}:activate', (c) => {
const id = c.req.param('id')
return c.json({ id, action: 'activate' })
})
app.post('/users/:id{[^:]+}:deactivate', (c) => {
const id = c.req.param('id')
return c.json({ id, action: 'deactivate' })
})The |
Beta Was this translation helpful? Give feedback.
The earlier
/users/:id:activatesuggestion is the part to avoid. In Hono,:id:activateis parsed as one parameter name, not as:idplus a literal:activate.Use an explicit regexp on the parameter instead:
The
{[^:]+}part makesidstop before the literal colon. If you have many actions, a single route like/users/:idActionand splitting on:in the handler is simpler, but for a small fixed set the regexp route keeps the handlers explicit.