Files
TelegramMemeVault/miniapp/src/lib/api.js
T

50 lines
2.7 KiB
JavaScript
Raw Normal View History

2026-10-07 02:17:30 +04:00
import { get } from 'svelte/store'
import { jwt } from '../stores/auth.js'
const BASE = '/api'
async function request(method, path, body) {
const token = get(jwt)
const headers = { 'Content-Type': 'application/json' }
if (token) headers['Authorization'] = `Bearer ${token}`
const res = await fetch(BASE + path, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
})
if (!res.ok) {
const text = await res.text()
throw new Error(`${res.status}: ${text}`)
}
const ct = res.headers.get('content-type') ?? ''
return ct.includes('application/json') ? res.json() : null
}
export const api = {
// ── Auth ──────────────────────────────────────────────────────────────────
auth: (initData) => request('POST', '/auth/telegram', { initData }),
// ── Media ─────────────────────────────────────────────────────────────────
getMedia: (q) => request('GET', `/media${q ? `?q=${encodeURIComponent(q)}` : ''}`),
getDownloadUrl: (id) => request('GET', `/media/${id}/download-url`).then((r) => r?.url),
sendToChat: (id, queryId) => request('POST', `/media/${id}/send`, { queryId }),
updateMedia: (id, patch) => request('PATCH', `/media/${id}`, patch),
deleteMedia: (id) => request('DELETE', `/media/${id}`),
// ── Collections ───────────────────────────────────────────────────────────
getCollections: () => request('GET', '/collections'),
createCollection: (name, description) => request('POST', '/collections', { name, description }),
updateCollection: (id, name, description) => request('PATCH', `/collections/${id}`, { name, description }),
deleteCollection: (id) => request('DELETE', `/collections/${id}`),
setCollectionInbox: (id) => request('PUT', `/collections/${id}/inbox`),
getCollectionItems: (id) => request('GET', `/collections/${id}/items`),
// ── Invites ───────────────────────────────────────────────────────────────
getInvites: (collectionId) => request('GET', `/collections/${collectionId}/invites`),
createInvite: (collectionId, role) => request('POST', `/collections/${collectionId}/invites`, { role }),
revokeInvite: (collectionId, inviteId) => request('DELETE', `/collections/${collectionId}/invites/${inviteId}`),
}