DB and Transaction types
I am creating a drizzle instance like this
Now I want to allow for functions to pass in a transaction or drizzle db
I am somewhat lost on the types.
Or is there a better way of allowing for optional transactions in a function?
19 Replies
@tcurdt For
DB
, you can type it as typeof db
; Transaction
can be types as PgTransaction<PostgresJsQueryResultHKT>
.
If you're using RQB, you'd do this: PgTransaction<PostgresJsQueryResultHKT, typeof schema>
Thanks, @Mario564 ... When I use
typeof db
it complains.
But this looks better so far.
Not entirely sure why this is better though.typeof db
should be almost the same as what you did aboveBut there seems to be a problem caused by
& $client: any;
The only difference is that if you want access to the
$client
method, you have to add that to your definition (PostgresJsDatabase<typeof schema> & { $client: /* typeof your client instance */ }
I believe for postgres.js, it should be like this:
What's the
$client
for? And eslint complains about the {}
it suggests object
or unknown
It's not mandatory, you can leave it out if you want, but it allows you to easily access the client instance that Drizzle uses under the hood for querying the DB
A way to workaround the ESLint issue is to either ESLint ignore it or replace
{}
with NonNullable<unknown>
which both resolve to the same typeThat seems to work. Thank you so much.
Me and the TS typing system are somehow not getting friendly enough.
No worries. We'll eventually document how to type common variables like these sometime in the future to save people some headache
I spoke to soon.
The first one works just fine.
The 2nd one (with $client) gives
I guess I just go with the first version for now. But it would be nice to understand the difference that causes this here.
Can you show me the full type error?
Sure.
gives
Need more info on the last code block you gave. It shows what TS expects but doesn't contain what the error itself is
The complaint is on the
tx?
... you mean, you need to see where it is used?TS should be showing a more detailed error. Could you provide a screenshot of you hovering over the problematic line?
Hm ... it really is only providing that
Oh, that's strange
Not sure what to make of it, it seems like your editor isn't providing the full error, as it should look like this:
I just tried and switched editors. I had a hunch it might be the reason.
seems like the transaction type is slightly different
How does this work with node-postgres?
I figured it out on my own!
This worked for me.