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
parent
3bd19aec54
commit
ee83665c5e
|
@ -0,0 +1,5 @@
|
||||||
|
---
|
||||||
|
'@hono/trpc-server': patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Use honoReq's bodyCache to provide a body function for trpc's req
|
|
@ -22,7 +22,10 @@ export const trpcServer = ({
|
||||||
createContext,
|
createContext,
|
||||||
...rest
|
...rest
|
||||||
}: tRPCOptions): MiddlewareHandler => {
|
}: 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) => {
|
return async (c) => {
|
||||||
|
const canWithBody = c.req.method === 'GET' || c.req.method === 'HEAD'
|
||||||
const res = fetchRequestHandler({
|
const res = fetchRequestHandler({
|
||||||
...rest,
|
...rest,
|
||||||
createContext: async (opts) => ({
|
createContext: async (opts) => ({
|
||||||
|
@ -31,7 +34,16 @@ export const trpcServer = ({
|
||||||
env: c.env,
|
env: c.env,
|
||||||
}),
|
}),
|
||||||
endpoint,
|
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))
|
}).then((res) => c.body(res.body, res))
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue