T
tRPC

❓-help

is context cached?

JJavascriptMick2/25/2023
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?
Mmsalsbery2/25/2023
createContext is called for every request AFAIK but I thought I just read it was just once per set of batched requests…
JJavascriptMick2/25/2023
seems like createContext is indeed called for every request but the values on the context are already present on subsequent requests
Mmsalsbery2/25/2023
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…”.. 😅
JJavascriptMick2/25/2023
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.

Looking for more? Join the community!

Recommended Posts
JSON inferred router output not matchingHello. I have a procedure query which is returning Json from a postgresql db using Prisma. The type Best way to implement input based validation on a router procedureHi guys, bit of a noob. I have already created a 'protectedProcedure', ensuring the user is logged [Help] Turbo shared typesI have a turborepo with two apps (web and embed). web is a t3 stack and embed is a create-react-app.Cache SSG helper responseI'm using `createProxySSGHelpers` in GSSP with `ssr: false` in the global config. I trying to cacheInput is too big for a single dispatchI decided to try tRPC for my Crypto analytics dashboard. However, I'm having a hard time passing thetypesafe permissionsHi, So I wanted to infer all the procedures from my router recursively & assign a permission (stringawaiting for procedure & logging the response.Hi, I was wondering if there is a way to handle the return object via the post-middleware's? I know createCaller Dependency Injection in Middleware ctx ?`createCaller` makes it really easy to inject dependencies via anything that's created during the `cbest practices for organizing routes/procedures?i'm trying to find some practices/styles in which people generally define routes with trpc. currentlValidating input inside middleware declaration```js const enforceUserIsCreatorOfEvent = t.middleware(({ ctx, next, input }) => { if (!input.evenFetch errors on stale pagesRecently I have been getting a lot of fetch errors on stale pages, in particular ones that have querDistribute typesafe tRPC Client in an NPM libraryHi ! super fan of trpc over here. We are building a javascript sdk for our API that is essentiallyMutation or query for something that updates db, but runs on every app load?I have 2 operations that need to run before showing my app UI. Those operations perform updates in DWebsocket is not defined errorI'm getting a "WebSocket is not defined error" on my next app connected to an express backend. Any i