All files / src/lib/db user.ts

100% Statements 8/8
100% Branches 14/14
100% Functions 2/2
100% Lines 8/8

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 61 62 63 64 65 66 67 68 69                                                          46x 46x       46x 36x     10x                         11x 11x   11x                            
/**
 * User identity storage for telemetry.
 *
 * Stores user info fetched from Sentry API to set Sentry user context.
 */
 
import { getDatabase } from "./index.js";
import { runUpsert } from "./utils.js";
 
export type UserInfo = {
  userId: string;
  email?: string;
  username?: string;
  /** Display name (different from username) */
  name?: string;
};
 
type UserRow = {
  user_id: string;
  email: string | null;
  username: string | null;
  name: string | null;
};
 
/**
 * Get stored user info.
 * Returns undefined if no user info is stored.
 */
export function getUserInfo(): UserInfo | undefined {
  const db = getDatabase();
  const row = db.query("SELECT * FROM user_info WHERE id = 1").get() as
    | UserRow
    | undefined;
 
  if (!row) {
    return;
  }
 
  return {
    userId: row.user_id,
    email: row.email ?? undefined,
    username: row.username ?? undefined,
    name: row.name ?? undefined,
  };
}
 
/**
 * Store user info.
 * Overwrites any existing user info.
 */
export function setUserInfo(info: UserInfo): void {
  const db = getDatabase();
  const now = Date.now();
 
  runUpsert(
    db,
    "user_info",
    {
      id: 1,
      user_id: info.userId,
      email: info.email ?? null,
      username: info.username ?? null,
      name: info.name ?? null,
      updated_at: now,
    },
    ["id"]
  );
}