T
TanStack7mo ago
unwilling-turquoise

Server function dependency injection

What is the best way to DI something such as the db into the handler of a server fn? In remix for example we have getLoadContext which allows us to set up dependencies that get passed as the context argument to loaders and actions. Coming from remix my expectation was:
const getUserById = createServerFn({ method: 'GET' })
.validator(z.string())
// context serves as server side DI container for db/services/etc.
.handler(async ({ data, context }) => {
return context.db.query.users.findFirst({ where: eq(users.id, data) })
})
const getUserById = createServerFn({ method: 'GET' })
.validator(z.string())
// context serves as server side DI container for db/services/etc.
.handler(async ({ data, context }) => {
return context.db.query.users.findFirst({ where: eq(users.id, data) })
})
5 Replies
constant-blue
constant-blue7mo ago
cc @Tanner Linsley
wise-white
wise-white7mo ago
For now, middleware Or even global middleware Create a global middleware to inject the db instance into context
other-emerald
other-emerald3mo ago
there's currently nothing like this for server routes, right?
wise-white
wise-white3mo ago
Server routes can have middleware registered to them that run hierarchically
other-emerald
other-emerald3mo ago
found it a little unintuitive that server functions can have global middleware while server actions can't, but I think it's fine

Did you find this page helpful?