| |
|
|
| let creds = {}; |
|
|
| export function setCredentials(initData, accessToken) { |
| creds = initData ? { init_data: initData } : { access_token: accessToken || "" }; |
| } |
|
|
| function credsQuery() { |
| if (creds.init_data) return "init_data=" + encodeURIComponent(creds.init_data); |
| return "access_token=" + encodeURIComponent(creds.access_token || ""); |
| } |
|
|
| export async function callApi(path, extra = {}) { |
| const res = await fetch(path, { |
| method: "POST", |
| headers: { "Content-Type": "application/json" }, |
| body: JSON.stringify({ ...creds, ...extra }), |
| }); |
| if (!res.ok) { |
| const body = await res.json().catch(() => ({})); |
| throw new Error(body.detail || `Request failed (${res.status})`); |
| } |
| return res.json(); |
| } |
|
|
| export async function callApiGet(path) { |
| const res = await fetch(path + "?" + credsQuery(), { method: "GET" }); |
| if (!res.ok) { |
| const body = await res.json().catch(() => ({})); |
| throw new Error(body.detail || `Request failed (${res.status})`); |
| } |
| return res.json(); |
| } |
|
|
| export async function callApiDelete(path) { |
| const res = await fetch(path + "?" + credsQuery(), { method: "DELETE" }); |
| if (!res.ok) { |
| const body = await res.json().catch(() => ({})); |
| throw new Error(body.detail || `Request failed (${res.status})`); |
| } |
| return res.json(); |
| } |
|
|