Tips for composing helpers in transactions

How are people managing composing reusable db queries that can be used standalone (db.(...)) and as part of a transaction?? Example (pseudocode)
function getUser() {
return db.select().from(Users).where(eq(Users.id, 1));
}

function getOrganization() {
return db.select().from(Orgs).where(eq(Orgs.id, 1));
}

// NOPE
function getUserAndOrganization() {
return db.transaction((tx) => {
const user = getUser();
const organization = getOrganization();
return { user, organization };
});
}
function getUser() {
return db.select().from(Users).where(eq(Users.id, 1));
}

function getOrganization() {
return db.select().from(Orgs).where(eq(Orgs.id, 1));
}

// NOPE
function getUserAndOrganization() {
return db.transaction((tx) => {
const user = getUser();
const organization = getOrganization();
return { user, organization };
});
}
3 Replies
Skel0
Skel03w ago
You can change the functions (or maybe in real code, class methods) to accept an optional tx object and use that instead
lordbinbash
lordbinbashOP3w ago
Was thinking something like this but would like to see if anybody has some nice tricks
export type DbOrTx = typeof db | Transaction;

export function getUser(client: DbOrTx = db) {
return client.select().from(Users).where(eq(Users.id, 1));
}
export type DbOrTx = typeof db | Transaction;

export function getUser(client: DbOrTx = db) {
return client.select().from(Users).where(eq(Users.id, 1));
}
Skel0
Skel03w ago
something like that yeah

Did you find this page helpful?