All files / app-leaderboard/src accounts.ts

80% Statements 4/5
75% Branches 3/4
100% Functions 2/2
100% Lines 4/4

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                                    44x                           44x 44x                               15x                    
import { and, count, eq } from 'drizzle-orm';
import type { Database } from './db/client.ts';
import { avatarURL } from './avatars.ts';
import { refreshPlayedChartListings } from './charts.ts';
import { passkey, profile, user } from './db/schema.ts';
 
/** The signed-in player's own view of their account (`GET /api/v0/me`). */
export interface AccountSummary {
  handle: string;
  displayName: string;
  /** True for a guest: until the account has a way back in (a passkey, or a Discord / Google sign-in). */
  anonymous: boolean;
  passkeys: number;
  /** The player's icon: the uploaded one, or the generated one. */
  avatarUrl: string;
}
 
export async function loadAccount(db: Database, userId: string): Promise<AccountSummary | undefined> {
  const [[row], [{ passkeys }]] = await Promise.all([
    db
      .select({
        handle: profile.handle,
        displayName: profile.displayName,
        anonymous: user.isAnonymous,
        passkeyCount: user.passkeyCount,
        avatarKey: profile.avatarKey,
      })
      .from(user)
      .innerJoin(profile, eq(profile.userId, user.id))
      .where(eq(user.id, userId)),
    db.select({ passkeys: count() }).from(passkey).where(eq(passkey.userId, userId)),
  ]);
  Iif (row === undefined) return undefined;
  return {
    handle: row.handle,
    displayName: row.displayName,
    anonymous: row.anonymous === true,
    passkeys: row.passkeyCount ?? passkeys,
    avatarUrl: avatarURL(row.handle, row.avatarKey),
  };
}
 
/**
 * Turns a guest account into a regular one once it has a way back in (a passkey, or a Discord / Google sign-in): the
 * player can now sign back in on any device, so its plays are listed under its handle like everyone else's instead of
 * behind the "Guests" filter. The display
 * name generated for anonymous accounts becomes the regular default; a name the player chose is kept.
 */
export async function claimAccount(db: Database, userId: string): Promise<void> {
  await db.batch([
    db.update(user).set({ isAnonymous: false }).where(eq(user.id, userId)),
    db
      .update(profile)
      .set({ displayName: 'Player' })
      .where(and(eq(profile.userId, userId), eq(profile.displayName, 'Anonymous'))),
    // The player now counts towards listing the charts they played (the batch runs in order, after the first update).
    refreshPlayedChartListings(db, userId),
  ]);
}