Is there any benefit to putting the db connection in the context versus having it as an global var?
Can I do this?
or in this way i have a benefit?
Solution:Jump to solution
Can you do it? Yes. Should you? I don't think so.
When you create variable outside the tRPC router, they're all declares immediately before the Requests Paths object. I'll give you an example:
```ts...
2 Replies
Solution
Can you do it? Yes. Should you? I don't think so.
When you create variable outside the tRPC router, they're all declares immediately before the Requests Paths object. I'll give you an example:
and then, when you go into the pages/api/[trpc] on the build folder:
all the variables are declared right before the object in which your endpoints are declared.
That is, these variable will be initiated for every single endpoint of the given router. That's not good. It would be problematic if there's a chance of them failing to initialize, so every endpoint would fail because of it. But that's not exclusive to here.
The context also lives within this file. If you go check, it will be after all routers, at the end. So, if you have Prisma within the context, and also another instance of Prisma in a another variable outside the endpoint scope, for every request at an endpoint of the given router, you will be initializing 2 instances of Prisma. One by declaring at the top of the file, the other one for every endpoint that uses the context.
Maybe you can do this if it's something exclusive to this particular router, since it's going to live within the router scope. Otherwise, it's not good.
But i would also say that it's not terrible, since that's probably going to be on serverless land, you'll only pay the price of initializing useless variables.
Anyway, take this with a grain of salt, i'm not a master of tRPC internals or anything. Hope this helps!
so it is a good idea only have the db conn inside the context
thank you for the explanation you were very clear