writing a transaction that calls functions
Hey everyone, I like what I've got going here but before I did this for my whole code base I just wanted to make sure I was on the right path
export async function createUser(user: NewUser, trx: Transaction<DB>) {
return db
.insertInto('User')
.values({
...user
})
.returningAll()
.executeTakeFirstOrThrow();
}
export async function createProfile(profile: NewProfile, trx: Transaction<DB>) {
return db
.insertInto('Profile')
.values({
...profile
})
.returningAll()
.execute();
}
export async function createBusiness(business: NewBusiness, trx: Transaction<trx>) {
return await db
.insertInto('Business')
.values({
...business
})
.returningAll()
.execute();
}
export async function createUserProfileBusiness(
user: NewUser,
profile: NewProfile,
business: NewBusiness
) {
try {
const result = await db.transaction().execute(async (trx) => {
const newUser = await createUser(user, trx);
const newProfile = await createProfile({ ...profile, userId: newUser.id }, trx);
const newBusiness = await createBusiness(business, trx);
return { newUser, newProfile, newBusiness };
});
return result;
} catch (error) {
// Handle the error here
console.error(error);
}
}export async function createUser(user: NewUser, trx: Transaction<DB>) {
return db
.insertInto('User')
.values({
...user
})
.returningAll()
.executeTakeFirstOrThrow();
}
export async function createProfile(profile: NewProfile, trx: Transaction<DB>) {
return db
.insertInto('Profile')
.values({
...profile
})
.returningAll()
.execute();
}
export async function createBusiness(business: NewBusiness, trx: Transaction<trx>) {
return await db
.insertInto('Business')
.values({
...business
})
.returningAll()
.execute();
}
export async function createUserProfileBusiness(
user: NewUser,
profile: NewProfile,
business: NewBusiness
) {
try {
const result = await db.transaction().execute(async (trx) => {
const newUser = await createUser(user, trx);
const newProfile = await createProfile({ ...profile, userId: newUser.id }, trx);
const newBusiness = await createBusiness(business, trx);
return { newUser, newProfile, newBusiness };
});
return result;
} catch (error) {
// Handle the error here
console.error(error);
}
}