Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions frontend/chat-ui/src/api.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
export const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';
const API_KEY = import.meta.env.VITE_API_KEY || '';

function buildUrl(path) {
const clean = path.startsWith('/') ? path : `/${path}`;
return API_BASE_URL ? `${API_BASE_URL.replace(/\/$/, '')}${clean}` : clean;
}

async function request(method, path, body) {
const headers = { 'x-api-key': API_KEY };
const url = buildUrl(path);
const headers = {};
if (API_KEY) headers['x-api-key'] = API_KEY;
const options = { method, headers };
if (body !== undefined) {
headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(body);
}

const res = await fetch(`${API_BASE_URL}${path}`, options);
const res = await fetch(url, options);
const text = await res.text();
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch (err) {
throw err;
// non-JSON response; preserve text in data
data = text;
}
}
if (!res.ok) {
Expand All @@ -33,4 +41,15 @@ export const post = (path, body) => request('POST', path, body);
export const put = (path, body) => request('PUT', path, body);
export const del = (path) => request('DELETE', path);

export default { get, post, put, del };
// Create an EventSource for SSE. Many servers don't accept custom headers for SSE,
// so we append the API key as a query parameter named `x-api-key` when present.
export function stream(path) {
let url = buildUrl(path);
if (API_KEY) {
const hasQuery = url.includes('?');
url = `${url}${hasQuery ? '&' : '?'}x-api-key=${encodeURIComponent(API_KEY)}`;
}
return new EventSource(url);
}

export default { get, post, put, del, stream };