Is it possible to run javascript between database transactions?

In my authentication flow, I need to do the following things on signup
  1. Check if user exists
  2. Check if email verification token exists
  3. If not, create new verification token
So.... instead of hitting the database 3 times, I thought it'd be a good idea to hit it once via a transaction. My understanding is that even if just querying twice and updating once, it's still better to do it all in one transaction. But wait....

Inbetween the db calls, I throw errors if the user or token already exists. When I think about it, if the queries are being sent to the database as one transaction and the erros thrown are written in javascript and inbetween those transactions, doesn't that mean the database won't run the code inbetween the transactions?

Can someone confirm that this will indeed need to be 3 transactions in order for me to throw properly. I can't do all this in one transaction because the errors won't throw right? Because the database won't receive the javascript.

For example (pseudo-code below):
await db.transaction(async tx => {
  const hasUser = await tx.query.users.findFirst(...); 
  if (hasUser) {
    throw new Error("User already exists"); 
  }
  // ^ This doesn't work right?

  const hasToken = await tx.query.token.findFirst(...);
  if (hasToken) {
    throw new Error("Token already exists");
  } 
  // ^ Neither does this?

  const token = await tx.insert(token).values(...);
});
Was this page helpful?