Vinnie
Vinnie2mo ago

Infer context from procedure after middleware

I'm using trpc version 10 on pnpm. I I have my handler functions in separate files from the routers themselves. I'm looking to type the context correctly based on the procedure the handler is used with. Currently I am setting the ctx type from the Context type that is inferred from the createContext function.
export type GetPreferencesHandlerOptions = {
ctx: Context;
};

export const getPreferencesHandler = async ({
ctx,
}: GetPreferencesHandlerOptions) => {
const { viewer } = ctx;
// /\
// ||
// Viewer | undefined

// ... rest of code
}
export type GetPreferencesHandlerOptions = {
ctx: Context;
};

export const getPreferencesHandler = async ({
ctx,
}: GetPreferencesHandlerOptions) => {
const { viewer } = ctx;
// /\
// ||
// Viewer | undefined

// ... rest of code
}
The context type should rather be inferred from the privateProcedure so the changes which are made to the context in middlewares will also be correctly typed. I did see the inferProcedureBuilderResolverOptions helper type, but it is only available in version 11, and version 11 hasn't been released yet. Is there a way to do this in v10? https://trpc.io/docs/server/procedures#inferProcedureBuilderResolverOptions
Define Procedures | tRPC
A procedure is a function which is exposed to the client, it can be one of:
Solution:
Okay I didn't come up with a direct solution, but I did solve it in a different way. Instead of just having the handler functions be in separated files. These -> .mutation(handlerFunc) I moved the whole creation of the procedure into seprate files. This way you can put the handler function directly into the .mutation call. This way the options (so also the context) are correctly inferred and the need to import the Context type becomes unnecessary. ```ts...
Jump to solution
1 Reply
Solution
Vinnie
Vinnie2mo ago
Okay I didn't come up with a direct solution, but I did solve it in a different way. Instead of just having the handler functions be in separated files. These -> .mutation(handlerFunc) I moved the whole creation of the procedure into seprate files. This way you can put the handler function directly into the .mutation call. This way the options (so also the context) are correctly inferred and the need to import the Context type becomes unnecessary.
export const getPreferencesProcedure = privateProcedure.query(
async ({ ctx }) => {
const { viewer } = ctx;
// /\
// ||
// Viewer

// ... rest of code
}
);
export const getPreferencesProcedure = privateProcedure.query(
async ({ ctx }) => {
const { viewer } = ctx;
// /\
// ||
// Viewer

// ... rest of code
}
);
Hope this helps other people witht he same problem :)