32 lines
1.8 KiB
TypeScript
32 lines
1.8 KiB
TypeScript
|
|
import { getTelegramInitData } from './telegram'
|
||
|
|
|
||
|
|
const API_BASE = import.meta.env.VITE_API_BASE_URL || ''
|
||
|
|
|
||
|
|
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||
|
|
const headers = new Headers(init.headers)
|
||
|
|
headers.set('Content-Type', 'application/json')
|
||
|
|
const initData = getTelegramInitData()
|
||
|
|
if (initData) headers.set('X-Telegram-Init-Data', initData)
|
||
|
|
const response = await fetch(`${API_BASE}${path}`, { ...init, headers })
|
||
|
|
const data = await response.json().catch(() => ({}))
|
||
|
|
if (!response.ok) {
|
||
|
|
const message = data?.detail?.message || data?.detail || response.statusText || 'API request failed'
|
||
|
|
throw new Error(String(message))
|
||
|
|
}
|
||
|
|
return data as T
|
||
|
|
}
|
||
|
|
|
||
|
|
export const api = {
|
||
|
|
tasks: () => request<{ tasks: any[]; groups: Record<string, any[]> }>('/api/tasks'),
|
||
|
|
task: (id: string) => request<{ task: any }>(`/api/tasks/${id}`),
|
||
|
|
events: (id: string) => request<{ events: any[] }>(`/api/tasks/${id}/events`),
|
||
|
|
runs: (id: string) => request<{ runs: any[] }>(`/api/tasks/${id}/runs`),
|
||
|
|
log: (id: string) => request<{ log: string; missing: boolean }>(`/api/tasks/${id}/log`),
|
||
|
|
create: (payload: Record<string, unknown>) => request<{ task: any }>('/api/tasks', { method: 'POST', body: JSON.stringify(payload) }),
|
||
|
|
comment: (id: string, body: string) => request(`/api/tasks/${id}/comment`, { method: 'POST', body: JSON.stringify({ body }) }),
|
||
|
|
action: (id: string, action: 'promote' | 'unblock' | 'archive') => request(`/api/tasks/${id}/${action}`, { method: 'POST' }),
|
||
|
|
block: (id: string, reason: string) => request(`/api/tasks/${id}/block`, { method: 'POST', body: JSON.stringify({ reason }) }),
|
||
|
|
assign: (id: string, assignee: string) => request(`/api/tasks/${id}/assign`, { method: 'POST', body: JSON.stringify({ assignee }) }),
|
||
|
|
dispatch: () => request('/api/dispatch', { method: 'POST' }),
|
||
|
|
}
|