All files / munch-ease-frontend/src/api auth.ts

0% Statements 0/30
0% Branches 0/1
0% Functions 0/1
0% Lines 0/30

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                                                             
import { api } from '@/api/client'
import type { Person } from '@/domain/types'

let cachedUser: Person | null = null

export async function currentUser(): Promise<Person | null> {
  if (cachedUser) return cachedUser
  try {
    const res = await api.POST('/api/v1/auth/refresh', { params: { cookie: { user_id: 0 } } })
    if (!res.response.ok) return null
    cachedUser = res.data ?? null
  } catch (_) {
    cachedUser = null
  }
  return cachedUser
}

export async function login(username: string): Promise<Person> {
  const res = await api.POST('/api/v1/auth/login', { body: { username } })
  if (!res.response.ok) {
    const err = res.error
    throw (
      (err instanceof Error && err) ||
      (typeof err === 'string' ? new Error(err) : new Error(`${res.response.status} ${res.response.statusText || 'HTTP error'}`))
    )
  }
  cachedUser = res.data ?? null
  if (!cachedUser) throw new Error('Login failed: empty response')
  return cachedUser
}