T
tRPC

I want to create a wrapper for TRPC.init but I can't seem to get the context type correct.

I want to create a wrapper for TRPC.init but I can't seem to get the context type correct.

KKatzius10/20/2023
I want to get wrap trpc.init create-context.ts
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>>
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>>
and I want to do:
function makeTRPC<T>() {
const t = initTRPC.context<Context<T>>().create({
errorFormatter({shape}) {
return shape
},
})
return t
}
function makeTRPC<T>() {
const t = initTRPC.context<Context<T>>().create({
errorFormatter({shape}) {
return shape
},
})
return t
}
but when I do:
const t = makeTRPC<{test: string}>()
const t = makeTRPC<{test: string}>()
t.context is of type {} when I do that 😦
SSandvich10/21/2023
You do Awaited<typeof createContext> but createContext isn't async so that doesn't do anything. I'd recommend just starting over with initTRPC.context<{test: string}>.create(...); and keep building up slowly to the more complex type you have until you find the error you made
KKatzius10/22/2023
it works, the problem is with the generic type makeTRPC<T> always resolves to {} even without the Awaited, it results in the same output thanks for the answer by th eway was able to resolve it using type inference: type LocalContext<T> = inferAsyncReturnType<typeof createInternalContext<T>> export type Context<T> = T extends infer R ? LocalContext<R> : never

Looking for more? Join the community!

T
tRPC

I want to create a wrapper for TRPC.init but I can't seem to get the context type correct.

Join Server
Recommended Posts
Trouble getting a TRPC client in Astro SSR pages, instead I get a noopI'd like to add TRPC to an Astro site. I have an SSR route here (https://github.com/aisflat439/anothWhy webhooks does not work with TRPC?I have a what suppose to be a webhook: ``` deposit: publicProcedure.input(z.any()).mutation(asynctRPC set up errorHey guys, I've been trying to set up tRPC, but unfortunatyy getting this error and it is really unclVercel maxDuration with tRPCHow do you extend extend tRPC timeouts on Vercel? I tried this in `vercel.json`: ```json { "functWhere is client side error handling documented?In the docs, I can only find error handling for the backend. But I want to get the TRPCError code indoes api.myQuery.invalidate() works if the query is not made at the first place?from testing, the invalidate runs the query, but it shouldn't because there is no cache? how do i iworking with custom errors and trpc errorFormatterHey guys. I'm trying to refactor my app so that all errors extend a BaseError class to make dealing tRPC and OpenTelemetryDoes anyone have experience with instrumenting tRPC with OTEL for tracing? It would be pretty neat Multiple TRPC endpoints on same API, with discrete clients? Any gotchas?I'm building a Sveltekit app that has several pages that will need to behave like SPA's. Rather thanProper way to revalidate SSR but from Client Side, ie. after a success Mutation.This question has been also posted on an specific thread but posting this here will allow people to How to implement tRPC auth ?Do you have any article/github links for how can i create auth in tRPC ?tRPC middleware infer type from another protectedProcedureHello, `protectedProcedure` check and adds a not nullable user to the ctx. However the `studyMiddlewtRPC requests on client vs server for NextJsHello, I'm new to tRPC, and am confused on one thing. I have watched videos of some using a server cpassing user input state variable to all api callsI have a multi organization app and need a way of passing the current organizationId on all requestsIs there a way to extract a procedure signature?I'm looking into extracting certain handlers into functions to keep certain procedures more manageabIs there a pattern for omitting certain types of errors from being returned in the API responseI'd prefer not to expose the ORM queries being used in my resolver. I'm already providing an `onErroDynamic input not leading to changes on the front endI'm building a dynamic procedure to access my database via Drizzle ORM. Ideally a developer would btRPC with with react-query prefetching in Next.js app directory.Hi. What is currently the best way to do prefetching in Next.js app directory when using @tanstack/r