Passing transaction to functions

Hey everyone. Quite new to the drizzle sphere. Coming from Go, i am quite used to passing db transactions from function to function, to be able to orchestrate a bigger function from smaller ones. As an example, say i have some music track. each track can have multiple genres, and each genre could be associated with different tracks - a many-to-many relationship. Essentially, i would love to be able to create this chain of functions:
const getCompleteTrackById(id: number): Promise<CompleteTrack> => {
await db.transaction(async (tx) => {
const baseEvent = await getTrackById(tx, id);
const genres = await getTrackGenres(tx, id);
return {
...baseEvent,
genres,
}
})
const getCompleteTrackById(id: number): Promise<CompleteTrack> => {
await db.transaction(async (tx) => {
const baseEvent = await getTrackById(tx, id);
const genres = await getTrackGenres(tx, id);
return {
...baseEvent,
genres,
}
})
This, to make me able to use the getTrackGenres function independently for other types of queries, aswell as make code more readable. Is this possible somehow with TypeScript? Thanks in advance!
4 Replies
Angelelz
Angelelz2w ago
Yes, this is a common pattern in drizzle
mattiskristensen
mattiskristensenOP2w ago
Right, im posing a question though - how would i do this? Mosly how i would type the tx parameter.
Darren
Darren2w ago
export type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];

//next file
import { Transaction } from "....";
export const getTrackById = async (db: Transaction, id: number) => {

const track = await db.select().from(tracks).where(eq(tracks.id, id))
//
return track

}
export type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];

//next file
import { Transaction } from "....";
export const getTrackById = async (db: Transaction, id: number) => {

const track = await db.select().from(tracks).where(eq(tracks.id, id))
//
return track

}
think this is one way, tho your query just looks like a join would be sufficient, no need to make 2 queries
Angelelz
Angelelz2w ago
The trasaction object passed to the callback shares the structure with the db object returned by the drizzle fuction. Another way to type it is just typeof db if he's not planning to explicitely call tx.rollback(). But your suggestion is more precise
Want results from more Discord servers?
Add your server