is context cached?

If I put an object on the context that represents the User record from my database...
export async function createContext(event: H3Event){
if (!dbUser) {
const userService = new UserService();
dbUser = await userService.getUser(user_id);
}

return {
dbUser,
blah....
}
};
export async function createContext(event: H3Event){
if (!dbUser) {
const userService = new UserService();
dbUser = await userService.getUser(user_id);
}

return {
dbUser,
blah....
}
};
And then I have a router function which changes important details of the user....
changeAccountLevel: protectedProcedure
.input(z.object({ user_id: z.number(), level: z.number() }))
.query(async ({ ctx, input }) => {
const userService = new UserService();
const user = await userService.changeAccountLevel(input.user_id, input.level);
return {
user,
}
}),
changeAccountLevel: protectedProcedure
.input(z.object({ user_id: z.number(), level: z.number() }))
.query(async ({ ctx, input }) => {
const userService = new UserService();
const user = await userService.changeAccountLevel(input.user_id, input.level);
return {
user,
}
}),
Do I need to 'mutate' the dbUser on the context....
ctx.dbUser = user
ctx.dbUser = user
or will subsequent calls to routes, re-invoke createContext and re-load the user from the database?
4 Replies
mark salsbery
mark salsbery2y ago
createContext is called for every request AFAIK but I thought I just read it was just once per set of batched requests…
JavascriptMick
seems like createContext is indeed called for every request but the values on the context are already present on subsequent requests
mark salsbery
mark salsbery2y ago
I don’t see how, I’m missing something I guess your dbUser reference exists outside of createContext so yeah you’d have to handle that however you need to. That’s a JavaScript thing, not tRPC specific Back to the original post, you could mutate ctx.dbUser but next request will use whatever dbUser was. Subsequent createContext calls aren’t going to refresh dbUser unless it’s falsey. dbUser is already “cached” somewhere according to your code sample so you’ll need to manage it Edit: I should have stated “you could mutate the value of ctx.dbUser…”.. 😅
JavascriptMick
aha, thanks @msalsbery you are right, I accidentally introduced 'caching' because I am defining the variable for dbUser outside the createContext function.....
let dbUser: FullDBUser | null

export async function createContext(event: H3Event){
if (!dbUser) {....etc
let dbUser: FullDBUser | null

export async function createContext(event: H3Event){
if (!dbUser) {....etc
..... which in hindsight is REALLY STOOPID, the example I followed treated the db connection (i.e.. prisma) in this way but then loaded the user fresh on each call to context... this is the way.