Replies: 1 comment 1 reply
-
A couple things... The tx object is almost the same type as the db object. It only has the rollback method that literally just throws an error.
Totally fine When you execute a transaction you are literally just executing the following query: That's all there is to it. import { db } from "@/lib/drizzle"
export async function createPost(trx: typeof db, title) { // <-- totally fine
await trx.insert(posts).values({ title })
} That's my understanding of transactions, if I'm wrong (I very well could be) somebody please correct me. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
It's a good practice to make services datasource injectable. Let's start with this code:
Problem
The problem with this code is: I can't execute
createPost
inside a transaction. I can't pass a transaction to it.If I change it to something like that
In this case, my function always needs a transaction and won't work just as normal query.
Current Workaround
Currently, we can implement the DataSource interface like this:
then we can use it like this:
or with classes
So by using this pattern, you can build services that can be used with or without transaction. also you can use nested service calls in a single transaction.
Idea
Drizzle should provide us with a
DataSource
interface using a helper type.Beta Was this translation helpful? Give feedback.
All reactions