46 lines
1.1 KiB
TypeScript
46 lines
1.1 KiB
TypeScript
export type User = {
|
|
id: string
|
|
username: string
|
|
}
|
|
|
|
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
|
const response = await fetch(path, {
|
|
...options,
|
|
credentials: 'include',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...options.headers,
|
|
},
|
|
})
|
|
if (!response.ok) {
|
|
const body = await response.json().catch(() => ({ detail: response.statusText }))
|
|
throw new Error(body.detail ?? `Request failed: ${response.status}`)
|
|
}
|
|
if (response.status === 204) {
|
|
return undefined as T
|
|
}
|
|
return response.json() as Promise<T>
|
|
}
|
|
|
|
export function register(username: string, password: string): Promise<User> {
|
|
return request<User>('/auth/register', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ username, password }),
|
|
})
|
|
}
|
|
|
|
export function login(username: string, password: string): Promise<User> {
|
|
return request<User>('/auth/login', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ username, password }),
|
|
})
|
|
}
|
|
|
|
export function logout(): Promise<void> {
|
|
return request<void>('/auth/logout', { method: 'POST' })
|
|
}
|
|
|
|
export function me(): Promise<User> {
|
|
return request<User>('/auth/me')
|
|
}
|