feat: scaffold React frontend with login/register UI
This commit is contained in:
45
frontend/src/api.ts
Normal file
45
frontend/src/api.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
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')
|
||||
}
|
||||
Reference in New Issue
Block a user