michaelp7725
michaelp7725
TtRPC
Created by michaelp7725 on 11/4/2024 in #❓-help
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
2 replies