A more modular way to combine predefined query into a single transaction

Hello currently I write my query into something like this
export const addUser = (data: InsertUser) => {
return db.insert(users).values(data).returning();
};


export const getUserByEmail = (email: string) => {
return db.select().from(users).where(eq(users.email, email));
};

async insertParticipant(userID : number, eventID: number) {
return db.insert(participants).values({userID,eventID}).returning()
}
export const addUser = (data: InsertUser) => {
return db.insert(users).values(data).returning();
};


export const getUserByEmail = (email: string) => {
return db.select().from(users).where(eq(users.email, email));
};

async insertParticipant(userID : number, eventID: number) {
return db.insert(participants).values({userID,eventID}).returning()
}
This function sometimes called separately, but there are times that I wanted to combine those query into a single transaction. What I do right now is creating a whole new transaction query without reusing the query above something like
const res = db.transactions((tx)=>{
let user : undefined | selectUsers
user = await tx.select().from(users).where(eq(users.email,email)
if(!user){
//insert a new user
user = await tx.insert(users).values({....}).returning()
}

const join = await tx.insert(participant).values({a: user.ID, b:fk.ID}).returning()

return {
...user,
...join
}

return res
})
const res = db.transactions((tx)=>{
let user : undefined | selectUsers
user = await tx.select().from(users).where(eq(users.email,email)
if(!user){
//insert a new user
user = await tx.insert(users).values({....}).returning()
}

const join = await tx.insert(participant).values({a: user.ID, b:fk.ID}).returning()

return {
...user,
...join
}

return res
})
as you can see it's seems inefficient, since the query is the same with those 3 defined function, is there any way i can utilize it and use it into transaction ? i suspect that i can use a QueryBuilder or something a suggestion would be very much appreciated
2 Replies
rphlmr ⚡
rphlmr ⚡6mo ago
https://drizzle.run/lt295lgldz4avpzwdee7ddhd You will need some inversion of control here
IgnisMurasaki
IgnisMurasakiOP6mo ago
Thankyou very much, it's very helpfull for me. it's really helping me a lot
Want results from more Discord servers?
Add your server