Skip to content

Commit

Permalink
feat: Use honoReq's bodyCache to provide a body function for trpc's r…
Browse files Browse the repository at this point in the history
…eq (#850)

Some middleware (in createContext) may need to read the body. If the raw request instance is provided directly, the body will be consumed prematurely, blocking the development of middleware.
  • Loading branch information
Gaubee authored Dec 2, 2024
1 parent 3bd19ae commit ee83665
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/chilly-experts-sneeze.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hono/trpc-server': patch
---

Use honoReq's bodyCache to provide a body function for trpc's req
14 changes: 13 additions & 1 deletion packages/trpc-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ export const trpcServer = ({
createContext,
...rest
}: tRPCOptions): MiddlewareHandler => {
const bodyProps = new Set(['arrayBuffer', 'blob', 'formData', 'json', 'text'] as const)
type BodyProp = typeof bodyProps extends Set<infer T> ? T : never
return async (c) => {
const canWithBody = c.req.method === 'GET' || c.req.method === 'HEAD'
const res = fetchRequestHandler({
...rest,
createContext: async (opts) => ({
Expand All @@ -31,7 +34,16 @@ export const trpcServer = ({
env: c.env,
}),
endpoint,
req: c.req.raw,
req: canWithBody
? c.req.raw
: new Proxy(c.req.raw, {
get(t, p, r) {
if (bodyProps.has(p as BodyProp)) {
return () => c.req[p as BodyProp]()
}
return Reflect.get(t, p, r)
},
}),
}).then((res) => c.body(res.body, res))
return res
}
Expand Down

0 comments on commit ee83665

Please sign in to comment.