2023-02-04 22:37:15 +08:00
|
|
|
import type { AnyRouter } from '@trpc/server'
|
2024-05-04 10:33:29 +08:00
|
|
|
import type {
|
|
|
|
FetchCreateContextFnOptions,
|
|
|
|
FetchHandlerRequestOptions,
|
|
|
|
} from '@trpc/server/adapters/fetch'
|
2023-02-04 22:37:15 +08:00
|
|
|
import { fetchRequestHandler } from '@trpc/server/adapters/fetch'
|
2024-04-27 10:46:09 +08:00
|
|
|
import type { Context, MiddlewareHandler } from 'hono'
|
2023-02-04 22:37:15 +08:00
|
|
|
|
2024-05-04 10:33:29 +08:00
|
|
|
type tRPCOptions = Omit<
|
|
|
|
FetchHandlerRequestOptions<AnyRouter>,
|
|
|
|
'req' | 'endpoint' | 'createContext'
|
|
|
|
> &
|
|
|
|
Partial<Pick<FetchHandlerRequestOptions<AnyRouter>, 'endpoint'>> & {
|
|
|
|
createContext?(
|
|
|
|
opts: FetchCreateContextFnOptions,
|
|
|
|
c: Context
|
|
|
|
): Record<string, unknown> | Promise<Record<string, unknown>>
|
|
|
|
}
|
2023-02-04 22:37:15 +08:00
|
|
|
|
2024-05-04 10:33:29 +08:00
|
|
|
export const trpcServer = ({
|
|
|
|
endpoint = '/trpc',
|
|
|
|
createContext,
|
|
|
|
...rest
|
|
|
|
}: tRPCOptions): MiddlewareHandler => {
|
2023-02-04 22:37:15 +08:00
|
|
|
return async (c) => {
|
|
|
|
const res = fetchRequestHandler({
|
2023-02-12 13:44:06 +08:00
|
|
|
...rest,
|
2024-04-29 12:04:45 +08:00
|
|
|
createContext: async (opts) => ({
|
2024-05-04 10:33:29 +08:00
|
|
|
...(createContext ? await createContext(opts, c) : {}),
|
2024-04-27 10:46:09 +08:00
|
|
|
// propagate env by default
|
|
|
|
env: c.env,
|
|
|
|
}),
|
2023-02-12 13:44:06 +08:00
|
|
|
endpoint,
|
2023-02-18 22:37:25 +08:00
|
|
|
req: c.req.raw,
|
2023-02-04 22:37:15 +08:00
|
|
|
})
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
}
|