Hi,
I have a procedure (technically, it's called procedure builder as an internal type) that is updating context. I want to reuse object of this context in an external function, but I have hard time extracting it.
E.g.:
import { initTRPC, TRPCError } from "@trpc/server";
type UnauthorizedContext = {
req: NextApiRequest;
res: NextApiResponse;
};
const { router, procedure, middleware } = initTRPC.context<UnauthorizedContext>().create();
const authProcedure = t.procedure.use(
t.middleware(async ({ ctx, next }) => {
const authObject = getAuthObject(ctx.req);
if (!authObject) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Not authorized",
});
}
return next({
ctx: { ...ctx, auth: authObject, },
});
}),
);
type Auth = {
// this is type I want to infer
}
const getDataByAuth = (auth: Auth) => {
// do stuff
}
const procedure = authProcedure
.mutation(async ({ ctx }) => {
const data = getDataByAuth(ctx.auth);
return data;
});
export const appRouter = t.router({ procedure });
Currently I infer type like that:
type ProcedureParams<P extends ProcedureBuilder<any>> = P extends ProcedureBuilder<infer X> ? X : never;
type ProcedureContext<P extends ProcedureBuilder<any>> = ProcedureParams<P>["_ctx_out"];
type Auth = ProcedureContext<typeof authProcedure>
I believe this might be extract as a helper.
type ProcedureParams<P extends ProcedureBuilder<any>> = P extends ProcedureBuilder<infer X> ? X : never;
export type inferProcedureContext<P extends ProcedureBuilder<any>> = ProcedureParams<P>["_ctx_out"];
// This might be useful to someone as well though I don't have a use case
export type inferProcedureMeta<P extends ProcedureBuilder<any>> = ProcedureParams<P>["_meta"];
Bring your own type inferrers
No response
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too