import {inferAsyncReturnType} from '@trpc/server'
import type {
CreateFastifyContextOptions,
FastifyTRPCPluginOptions,
// eslint-disable-next-line
} from '@trpc/server/adapters/fastify'
/**
* Defines your inner context shape.
* Add fields here that the inner context brings.
*/
export interface CreateInnerContextOptions extends Partial<CreateFastifyContextOptions> {}
export function createContext(config: Partial<FastifyTRPCPluginOptions<any>>) {
return (outerOptions: CreateFastifyContextOptions) => {
return createInternalContext((innerOptions) => {
if (!outerOptions?.req || !outerOptions?.res) {
return innerOptions
}
return {
...innerOptions,
...config?.trpcOptions?.createContext?.({
req: outerOptions.req,
res: outerOptions.res,
}),
}
}, outerOptions)
}
}
/**
* Outer context. Used in the routers and will e.g. bring `req` & `res` to the context as "not `undefined`".
*
* @see https://trpc.io/docs/context#inner-and-outer-context
*/
async function createInternalContext<T>(
createContextInner: (opts?: CreateInnerContextOptions) => T,
opts: CreateFastifyContextOptions,
) {
const contextInner = createContextInner()
return {
...contextInner,
req: opts.req,
res: opts.res,
}
}
export type Context<T> = inferAsyncReturnType<(opts: T) => Awaited<typeof createContext>>