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

Transform request body #2467

Closed
cdtut opened this issue Apr 4, 2024 · 6 comments
Closed

Transform request body #2467

cdtut opened this issue Apr 4, 2024 · 6 comments
Labels
enhancement New feature or request.

Comments

@cdtut
Copy link

cdtut commented Apr 4, 2024

What is the feature you are proposing?

Routes get request body with functions like await c.req.json(). In middleware you should be able to intercept and change the value the route gets with something like c.req.setJson(someTransformMethod(await c.req.json())).

@cdtut cdtut added the enhancement New feature or request. label Apr 4, 2024
@NicoPlyley
Copy link
Contributor

If you would like to do that in the meantime, you can use c.set() / c.get() and pass the updated data to your route that way instead

@yusukebe
Copy link
Member

yusukebe commented May 7, 2024

As @NicoPlyley said, we can use c.set() / c.get(). Closing this.

@yusukebe yusukebe closed this as completed May 7, 2024
@cdtut
Copy link
Author

cdtut commented May 8, 2024

@yusukebe c.get() doesn't have same benefit. If some routes body need to be transformed and others don't it is inconsistent. Some will have to use c.get().json and others use c.req.json() which is confusing and bring mistakes.

If possible to transform a body before getting to route all route can use c.req.json() and know it is right data.

@yusukebe
Copy link
Member

yusukebe commented May 8, 2024

@cdtut

This way is not recommended because this API is for internal usage, but you can make it with the code:

app.use('*', async (c, next) => {
  const data = await c.req.json()
  //
  c.req.bodyCache.json = 'transformeddata'
  await next()
})

app.post('/', async (c) => {
  const data = await c.req.json()
  return c.json(data)
})

@cdtut
Copy link
Author

cdtut commented May 8, 2024

Can internal c.req.bodyCache.json = data have external API like c.req.setJson(data) so can be used reliably? For all body requests not just json.

@yusukebe
Copy link
Member

yusukebe commented May 8, 2024

Can internal c.req.bodyCache.json = data have external API like c.req.setJson(data) so can be used reliably?

No. Basically, the Request body should be immutable, and we don't want to add more methods to the c.req.

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

No branches or pull requests

3 participants