feat: Use honoReq's bodyCache to provide a body function for trpc's req (#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.
pull/862/head
Gaubee 2024-12-02 09:08:18 +08:00 committed by GitHub
parent 3bd19aec54
commit ee83665c5e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 1 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/trpc-server': patch
---
Use honoReq's bodyCache to provide a body function for trpc's req

View File

@ -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) => ({
@ -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
}