File size: 900 Bytes
9d2d895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { getCurrentClerkUser } from './clerk';

/**
 * Account-scoped requests may settle after Clerk has selected another user.
 * Never let a result (or an account-specific error) cross that handoff.
 */
export function isAccountStillCurrent(userId: string): boolean {
  return getCurrentClerkUser()?.id === userId;
}

export function assertAccountStillCurrent(userId: string, action: string): void {
  if (!isAccountStillCurrent(userId)) {
    throw new Error(`Account changed while ${action}. Try again.`);
  }
}

export async function settleAccountOperation<T>(
  userId: string,
  action: string,
  operation: () => Promise<T>,
): Promise<T> {
  assertAccountStillCurrent(userId, action);
  let result: T;
  try {
    result = await operation();
  } catch (err) {
    assertAccountStillCurrent(userId, action);
    throw err;
  }
  assertAccountStillCurrent(userId, action);
  return result;
}