types for database/transaction

Hey, I have this function:
export const userRelationExists = async (
...,
database
) => {
return database.query.users.findFirst({
...
});
}
export const userRelationExists = async (
...,
database
) => {
return database.query.users.findFirst({
...
});
}
You can see, that I get a database as variable. That can either be a default postgres database (easy to type) or it can be a transaction (how to type). I would like to know how to type them correctly, so I can use users in this case? I could do something like this:
database: PgTransaction<any, any, any> | PgDatabase<any>
database: PgTransaction<any, any, any> | PgDatabase<any>
But then I can access users via database.query.users :/
6 Replies
B33fb0n3
B33fb0n3OP8mo ago
solved it by just removing the database stuff and only return the config:
export const findUserWithRelationsConfig = (
...,
) => {
return {
...
}
}
export const findUserWithRelationsConfig = (
...,
) => {
return {
...
}
}
francis
francis8mo ago
this is how I do it
export type DrizzleTransaction = Parameters<Parameters<DrizzleClient["transaction"]>[0]>[0];
export type DrizzleTransaction = Parameters<Parameters<DrizzleClient["transaction"]>[0]>[0];
where DrizzleClient is ReturnType<typeof drizzle> it's obnoxious, but it works, and lets me pass around the tx variable alternatively, if you have a drizzle instance bound to a schema, just use the typeof that instead
B33fb0n3
B33fb0n3OP8mo ago
Ohh starts smart. Will do that in the future. Thanks! 🙏
code9
code94mo ago
Hey guys, do you have this working? Because i still get an error when doing something like trx.query.user.findFirst where ts complains about excessive stack depth comparing types...
B33fb0n3
B33fb0n3OP4mo ago
I modified mine a bit to get it working. Now I have it like this and it works perfectly:
export type DrizzleTransaction = PgTransaction<PostgresJsQueryResultHKT, typeof import("@/lib/database/schema"), ExtractTablesWithRelations<typeof import("@/lib/database/schema")>>;
export type DrizzleTransaction = PgTransaction<PostgresJsQueryResultHKT, typeof import("@/lib/database/schema"), ExtractTablesWithRelations<typeof import("@/lib/database/schema")>>;
francis
francis4mo ago
ah, I don't use the query api. that must be why mine works, I just use it as a sql client
Want results from more Discord servers?
Add your server