michaelp7725
michaelp77252mo ago

What are the benefits of adding db to context rather than importing it directly in the router?

As per title, the docs and most examples I've seen using TRPC put the database into context as follows,
import db from "../db";
export const createContext = async (opts: CreateNextContextOptions) => {

return {
db,
};
};

import db from "../db";
export const createContext = async (opts: CreateNextContextOptions) => {

return {
db,
};
};

can anyone explain what the actual benefit of this is over just importing it in the routers like below?
import { protectedProcedure, router } from "../trpc";
import { eq } from "drizzle-orm";
import { db } from "../db";
import {
clients,
} from "../schemas/clients.schema";

export default router({
update: protectedProcedure
.input(getAllSchema)
.query(async ({ ctx, input }) => {
const updatedClient = await db
.update(clients)
.set(input)
.where(eq(clients.id, input.id))
.returning();
return updatedClient
}),
})
import { protectedProcedure, router } from "../trpc";
import { eq } from "drizzle-orm";
import { db } from "../db";
import {
clients,
} from "../schemas/clients.schema";

export default router({
update: protectedProcedure
.input(getAllSchema)
.query(async ({ ctx, input }) => {
const updatedClient = await db
.update(clients)
.set(input)
.where(eq(clients.id, input.id))
.returning();
return updatedClient
}),
})
I'm sure there must be some reasoning so I want to make sure I don't require a needless refactoring later on. Thanks! Michael
1 Reply
mh
mh2mo ago
it's a matter of preference. don't think there is any benefit or loss in either approach.

Did you find this page helpful?