Global dynamic parameter for many mutations/queries

Noob question, but is there a way to have a piece of data available to all queries in a certain router? I don’t want to constantly have to pass this parameter into all of the queries that use it. I WOULD store it in a session callback property but the value might change and idk if there is a way to manually update this value without having to sign-in again?
4 Replies
FluX
FluX3y ago
This is possible with a context: https://trpc.io/docs/context Copied an example from my Express/tRPC app:
export const createContext = ({ req, res }: CreateExpressContextOptions) => {
const userid = req.user as string
return {
userid
}
};

type Context = inferAsyncReturnType<typeof createContext>;

export const t = initTRPC.context<Context>().create();
export const createContext = ({ req, res }: CreateExpressContextOptions) => {
const userid = req.user as string
return {
userid
}
};

type Context = inferAsyncReturnType<typeof createContext>;

export const t = initTRPC.context<Context>().create();
export const userRouter = t.router({

// Gets the current logged in user - or not
me: publicProcedure
.query(async ({ctx})=> {
if (!ctx.userid) return null
const userdata = await user.getById(ctx.userid)
return userdata
}),
...
export const userRouter = t.router({

// Gets the current logged in user - or not
me: publicProcedure
.query(async ({ctx})=> {
if (!ctx.userid) return null
const userdata = await user.getById(ctx.userid)
return userdata
}),
...
Context | tRPC
Your context holds data that all of your tRPC procedures will have access to, and is a great place to put things like database connections or authentication information.
jix74
jix74OP3y ago
@Fluxium where would you typically store queries for things that will go in context?
FluX
FluX3y ago
I'm not exactly sure what you mean. In my case I have a "main" router and smaller "sub" routers:
export const trpcRouter = t.router({
user: userRouter,
});
export const trpcRouter = t.router({
user: userRouter,
});
export const userRouter = t.router({
me: publicProcedure
.query(async ({ctx})=> {
// whatever
}),
})
export const userRouter = t.router({
me: publicProcedure
.query(async ({ctx})=> {
// whatever
}),
})
And I can access the context wherever and whenever I need
jix74
jix74OP3y ago
@Fluxium Basically I have a different id that I would like to store inside of my context, but this id needs to be fetched from my database and then put into my context. Is that possible? You know what, I don't think context is the answer. I think I'm over thinking this and just need to have a reusable query within my router. This will be easy enough.

Did you find this page helpful?