is context cached?
If I put an object on the context that represents the User record from my database...
And then I have a router function which changes important details of the user....
Do I need to 'mutate' the dbUser on the context....
or will subsequent calls to routes, re-invoke createContext and re-load the user from the database?
4 Replies
createContext is called for every request AFAIK but I thought I just read it was just once per set of batched requests…
seems like createContext is indeed called for every request but the values on the context are already present on subsequent requests
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…”.. 😅
aha, thanks @msalsbery you are right, I accidentally introduced 'caching' because I am defining the variable for dbUser outside the createContext function.....
..... 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.