All files / src/services device.ts

38.88% Statements 7/18
0% Branches 0/4
60% Functions 3/5
37.5% Lines 6/16

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                  4x   2x             4x 4x       4x           4x                                
import Dexie from 'dexie'
import api from './api'
 
export interface DeviceInfo {
  id: string
  displayName: string | null
  createdAt: string
}
 
export const deviceService = {
  get: (deviceId: string): Promise<DeviceInfo> =>
    api.get<DeviceInfo>(`/devices/${deviceId}`).then(r => r.data),
}
 
class DeviceDb extends Dexie {
  meta!: Dexie.Table<{ key: string; value: string }, string>
 
  constructor() {
    super('listme-device')
    this.version(1).stores({ meta: 'key' })
  }
}
 
const db = new DeviceDb()
 
function generateUUID(): string {
  return crypto.randomUUID()
}
 
let cachedDeviceId: string | null = null
 
export async function getDeviceId(): Promise<string> {
  if (cachedDeviceId) return cachedDeviceId
 
  const row = await db.meta.get('deviceId')
  if (row) {
    cachedDeviceId = row.value
    return cachedDeviceId
  }
 
  const newId = generateUUID()
  await db.meta.put({ key: 'deviceId', value: newId })
  cachedDeviceId = newId
  return newId
}