| import type { ClientData } from "../types"; |
|
|
| export const DEV_API_BASE = "http://localhost:8000"; |
| export const API_BASE = |
| import.meta.env.VITE_API_BASE_URL ?? |
| (import.meta.env.DEV ? DEV_API_BASE : ""); |
| const DEV_CLIENT_ID = "ID_UNICO_DEL_CLIENTE_001"; |
|
|
| export interface ClientConfigResponse { |
| cliente: ClientData; |
| query: string; |
| } |
|
|
| export function getApiBase(customApiBase?: string) { |
| return customApiBase?.trim() ? customApiBase : API_BASE; |
| } |
|
|
| export function buildApiUrl(path: string, customApiBase?: string) { |
| return `${getApiBase(customApiBase)}${path}`; |
| } |
|
|
| export async function fetchClientConfig( |
| token: string, |
| clientId: string, |
| customApiBase?: string, |
| useDevToken = true, |
| ): Promise<ClientConfigResponse> { |
| let finalToken = token; |
| const finalClientId = clientId; |
|
|
| if (!finalToken && !finalClientId) { |
| if (!import.meta.env.DEV || !useDevToken) { |
| throw new Error("No se encontr贸 el token o key en la URL."); |
| } |
|
|
| const tokenRes = await fetch(buildApiUrl("/api/token", customApiBase), { |
| method: "POST", |
| headers: { "Content-Type": "application/x-www-form-urlencoded" }, |
| body: `client_id=${encodeURIComponent(DEV_CLIENT_ID)}`, |
| }); |
|
|
| if (!tokenRes.ok) { |
| throw new Error("No se pudo generar el token de prueba en desarrollo."); |
| } |
|
|
| const tokenData = await tokenRes.json(); |
| finalToken = tokenData.token; |
| } |
|
|
| const query = finalToken |
| ? `token=${encodeURIComponent(finalToken)}` |
| : `client_id=${encodeURIComponent(finalClientId)}`; |
|
|
| const res = await fetch(buildApiUrl(`/config?${query}`, customApiBase)); |
| if (!res.ok) { |
| const text = await res.text(); |
| throw new Error( |
| `No se pudo obtener la configuraci贸n del cliente. ${res.status} ${text}`, |
| ); |
| } |
|
|
| const cliente = await res.json(); |
| return { cliente, query }; |
| } |
|
|
| export interface UploadImageResponse { |
| filename: string; |
| [key: string]: unknown; |
| } |
|
|
| export async function uploadRoomImage( |
| file: File, |
| customApiBase?: string, |
| ): Promise<UploadImageResponse> { |
| const formData = new FormData(); |
| formData.append("file", file); |
|
|
| const response = await fetch( |
| buildApiUrl("/api/upload-image", customApiBase), |
| { |
| method: "POST", |
| body: formData, |
| }, |
| ); |
|
|
| if (!response.ok) { |
| const text = await response.text(); |
| throw new Error(text || "Error al subir la imagen"); |
| } |
|
|
| return response.json(); |
| } |
|
|
| export async function startSession(query: string, customApiBase?: string) { |
| await fetch(buildApiUrl("/session/start", customApiBase), { |
| method: "POST", |
| headers: { "Content-Type": "application/x-www-form-urlencoded" }, |
| body: query, |
| }); |
| } |
|
|