hono icon indicating copy to clipboard operation
hono copied to clipboard

Types for req.parsedBody

Open gkiely opened this issue 3 years ago • 3 comments

Is it possible to add the ability to pass a generic type to bodyParse? https://github.com/honojs/hono/blob/master/src/middleware/body-parse/index.ts#L7

Example:

app.post('/api/post/:id', bodyParse(), async c => {
  const body = c.req.parsedBody;
});
image

gkiely avatar Jul 03 '22 17:07 gkiely

That may be difficult, but it's a good theme. I'll give it some more thought.

yusukebe avatar Jul 03 '22 23:07 yusukebe

I closed it as I ended up using zod to validate it, as technically the payload is unknown at runtime. image

Perhaps moving it to type unknown would be good? It would prevent a user from having a runtime error.

gkiely avatar Jul 04 '22 00:07 gkiely

It is certainly one way to use zod. However, I think it's difficult to make it unknown because there are use cases to use parsedBody directly not using a validator such as zod.

For example, I think it's good to make it a function, like c.req.parsed body(). In this case, we can pass the generics easily.

const props = c.req.parsedBody<Props>()

Though, it's still in the planning stages.

yusukebe avatar Jul 04 '22 00:07 yusukebe