kbemasterK
tRPC2y ago
6 replies
kbemaster

Is there any benefit to putting the db connection in the context versus having it as an global var?

Can I do this?
export const challengesRouter = router({
  getChallengeById: privateProcedure
    .input(z.string().uuid())
    .query(async ({ input }) => {
      const challenge = await db.query.challengeTable.findFirst({
        where: (columns, { eq }) => eq(columns.sectionId, input),
        columns: {
          id: true,
          sectionId: true,
        },
      });
      return challenge;
    }),
});

or in this way i have a benefit?

export const challengesRouter = router({
  getChallengeById: privateProcedure
    .input(z.string().uuid())
    .query(async ({ input, ctx }) => {
      const challenge = await ctx.db.query.challengeTable.findFirst({
        where: (columns, { eq }) => eq(columns.sectionId, input),
        columns: {
          id: true,
          sectionId: true,
        },
      });
      return challenge;
    }),
});
Solution
I've wondered why I should use the tRPC context instead of just importing my database singleton from a module. Is there any benefit to it?

Because of TS performance issues, I'm creating multiple functions for bigger procedures. And passing the db connection around may be an unnecessary overhead.
What's the benefit of using the context instead of a direct import ...
Was this page helpful?