31 lines
961 B
TypeScript
31 lines
961 B
TypeScript
|
|
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
|
||
|
|
}
|