All files / src/services userId.ts

10% Statements 2/20
0% Branches 0/6
20% Functions 1/5
11.11% Lines 2/18

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    4x     1x                                                                                  
import Dexie from 'dexie'
 
const KEY = 'listme:userId'
 
export function getUserId(): string | null {
  return localStorage.getItem(KEY)
}
 
export function setUserId(id: string): void {
  localStorage.setItem(KEY, id)
}
 
export function getOrCreateUserId(): string {
  const existing = getUserId()
  if (existing) return existing
  const newId = crypto.randomUUID()
  setUserId(newId)
  return newId
}
 
// Called once before the app mounts.
// Migrates an existing deviceId from IndexedDB (old format) → localStorage userId.
class LegacyDeviceDb extends Dexie {
  meta!: Dexie.Table<{ key: string; value: string }, string>
  constructor() {
    super('listme-device')
    this.version(1).stores({ meta: 'key' })
  }
}
 
export async function initUserId(): Promise<void> {
  if (getUserId()) return // already set
 
  try {
    const db = new LegacyDeviceDb()
    const row = await db.meta.get('deviceId')
    if (row?.value) {
      setUserId(row.value)
      return
    }
  } catch {
    // IndexedDB unavailable (SSR, test env, etc.) — skip migration
  }
 
  setUserId(crypto.randomUUID())
}