Slow api request using a transaction

Hi I wondered if I can remove async out of the child transactions inside the transaction function, to increase performacne or run promise.allSettled Use case is I have some code like this which works, but it is slow.
const user = db.transaction(async (transaction) => {
const invite = await transaction
.update(invites)
.set({ claimed: true })
.where(eq(invites.email, data.email))
.returning();
const userData = !userExists
? await transaction
.insert(users)
.values({
...dataObject,
wasPreviouslyWaitlisted: false,
numberOfInvites: 3,
invitedBy: invite[0].createdBy
})
.returning()
: await transaction
.update(users)
.set({
...dataObject,
wasPreviouslyWaitlisted: true,
numberOfInvites: 3,
invitedBy: invite[0].createdBy,
approvalStatus: invite[0].inviteType === 'admin' ? 'approved' : 'pending'
})
.where(eq(users.email, data.email))
.returning();

await transaction.insert(coverageOptions).values(coverageItems).onConflictDoNothing();
await transaction.insert(tickers).values(tickersOptions).onConflictDoNothing();
await transaction
.insert(userCoverageOptions)
.values(coverageItems.map((item) => ({ userId: userData[0].id, coverageOptionId: item.id })))
.onConflictDoNothing();
await transaction
.insert(userTickers)
.values(tickersOptions.map((item) => ({ userId: userData[0].id, tickerId: item.id })))
.onConflictDoNothing();

return userData;
});
const user = db.transaction(async (transaction) => {
const invite = await transaction
.update(invites)
.set({ claimed: true })
.where(eq(invites.email, data.email))
.returning();
const userData = !userExists
? await transaction
.insert(users)
.values({
...dataObject,
wasPreviouslyWaitlisted: false,
numberOfInvites: 3,
invitedBy: invite[0].createdBy
})
.returning()
: await transaction
.update(users)
.set({
...dataObject,
wasPreviouslyWaitlisted: true,
numberOfInvites: 3,
invitedBy: invite[0].createdBy,
approvalStatus: invite[0].inviteType === 'admin' ? 'approved' : 'pending'
})
.where(eq(users.email, data.email))
.returning();

await transaction.insert(coverageOptions).values(coverageItems).onConflictDoNothing();
await transaction.insert(tickers).values(tickersOptions).onConflictDoNothing();
await transaction
.insert(userCoverageOptions)
.values(coverageItems.map((item) => ({ userId: userData[0].id, coverageOptionId: item.id })))
.onConflictDoNothing();
await transaction
.insert(userTickers)
.values(tickersOptions.map((item) => ({ userId: userData[0].id, tickerId: item.id })))
.onConflictDoNothing();

return userData;
});
1 Reply
Angelelz
Angelelz15mo ago
If you are running several queries that don't depend on each other inside a transaction. by all means run them parallel
Want results from more Discord servers?
Add your server