Frontend: unificar apiFetch en theme.js (elimina la triplicación)

El helper apiFetch estaba copiado en checada/becario/panel, y el arreglo de
"Content-Type solo si hay body" solo se había puesto en panel. Ahora vive una
sola vez en theme.js (window.Theme.apiFetch) y las tres páginas lo consumen con
`const { apiFetch } = Theme;`. Mismo comportamiento que antes —mismo origen,
credentials:'include', mapeo de error por code/status/data— solo cambia de
dónde viene, no qué hace.

El helper unificado ya no declara Content-Type en un POST sin cuerpo (el logout
del becario dejaba de dar un 400 que se tragaba el catch). Con el arreglo de
backend es doble red: el servidor ya tolera el cuerpo vacío de todos modos.

Verificado: las tres páginas montan y hacen su primer apiFetch real en Chrome
headless (panel→login, becario→acceso, checada→estado sin token); aprobar/baja/
rechazar/logout sin body → 200; peticiones con body → 201; checada y becario
conservan su comportamiento (candado).
This commit is contained in:
Collina Systems committed 2026-07-06 15:35:33 -06:00
1 parent 1141c17cc5
commit 8dd70a996b
4 files changed
+39 -53

No files matched your search

+4 -16
View File
@@ -24,22 +24,10 @@
<script type="text/babel" data-presets="react">
const { useState, useEffect, useCallback } = React;
// ─────────────────── Cableado al backend (SIN cambios) ───────────────────
const API_BASE = `${window.location.origin}/api`;
async function apiFetch(path, options = {}) {
const res = await fetch(`${API_BASE}${path}`, {
credentials: "include",
...options,
headers: { "Content-Type": "application/json", ...(options.headers || {}) },
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(data.error || `HTTP ${res.status}`);
err.code = data.code; err.status = res.status;
throw err;
}
return data;
}
// Cableado al backend: cliente HTTP compartido en theme.js, el mismo para las
// tres páginas. Mismo comportamiento de antes (mapeo de error por code/status);
// ahora vive en un solo sitio en vez de duplicado por página.
const { apiFetch } = Theme;
// Piel visual "cream" del rediseño, servida por theme.js (flavor 'becario' =
// móvil, mismos componentes y tokens que checada). Nada de colores inline.
+4 -16
View File
@@ -29,22 +29,10 @@ const { useState, useEffect } = React;
const UI = Theme.makeUI("checada");
const { Logo, IconBadge, Card, Btn, Input, Aviso, Estado, palette, fonts, icons } = UI;
// ─────────────────── Cableado al backend (SIN cambios) ───────────────────
const API_BASE = `${window.location.origin}/api`;
async function apiFetch(path, options = {}) {
const res = await fetch(`${API_BASE}${path}`, {
credentials: "include",
...options,
headers: { "Content-Type": "application/json", ...(options.headers || {}) },
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(data.error || `HTTP ${res.status}`);
err.code = data.code; err.status = res.status; err.data = data;
throw err;
}
return data;
}
// Cableado al backend: cliente HTTP compartido en theme.js, el mismo para las
// tres páginas. Mismo comportamiento de antes (mapeo de error por code/status/
// data); ahora vive en un solo sitio en vez de duplicado por página.
const { apiFetch } = Theme;
const fmtHoras = (h) => `${(h ?? 0).toLocaleString("es-MX", { maximumFractionDigits: 1 })} h`;
const fmtHM = (iso) => (iso ? new Date(iso).toLocaleTimeString("es-MX", { timeZone: "America/Mexico_City", hour: "2-digit", minute: "2-digit" }) : "");
+5 -20
View File
@@ -25,26 +25,11 @@
const { useState, useEffect, useCallback } = React;
// ═══════════════════════════════════════════════════════════
// Cableado al backend (SIN cambios). El panel se sirve detrás de nginx
// (mismo origen); credentials:'include' manda la cookie de sesión de la
// supervisora en cada request.
// ═══════════════════════════════════════════════════════════
const API_BASE = `${window.location.origin}/api`;
async function apiFetch(path, options = {}) {
// Content-Type JSON SOLO cuando hay body: Fastify rechaza un cuerpo vacío con
// application/json (FST_ERR_CTP_EMPTY_JSON_BODY → 400), lo que rompía todos los
// POST sin cuerpo (aprobar/baja/rechazar/logout). Con body, el header se pone.
const headers = { ...(options.headers || {}) };
if (options.body != null) headers["Content-Type"] = "application/json";
const res = await fetch(`${API_BASE}${path}`, { credentials: "include", ...options, headers });
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(data.error || `HTTP ${res.status}`);
err.code = data.code; err.status = res.status;
throw err;
}
return data;
}
// Cableado al backend: cliente HTTP compartido en theme.js, el mismo para las
// tres páginas. El panel se sirve detrás de nginx (mismo origen); la cookie de
// sesión de la supervisora viaja con credentials:'include'. Mismo mapeo de
// error por code/status que antes; ahora en un solo sitio.
const { apiFetch } = Theme;
// Piel cream de escritorio (theme.js, flavor 'panel'). Nada de colores inline.
const UI = Theme.makeUI("panel");
+26 -1
View File
@@ -578,5 +578,30 @@ window.Theme = (function () {
return { Btn: Btn, Card: Card, Input: Input, Badge: Badge, Field: Field, Estado: Estado };
}
return { COLORS: COLORS, FONT: FONT, SPACE: SPACE, RADIUS: RADIUS, makeUI: makeUI };
// ── Cliente HTTP compartido por checada/becario/panel ─────────────────────
// Vive UNA sola vez aquí (antes estaba duplicado en las tres páginas). Mismo
// origen detrás de nginx; credentials:'include' manda la cookie de sesión. El
// Content-Type JSON se declara SOLO cuando de verdad hay body: anunciarlo en
// un POST sin cuerpo hacía que Fastify respondiera 400. El error lleva
// code/status/data para que cada página mapee por `code` igual que antes.
async function apiFetch(path, options) {
options = options || {};
var headers = Object.assign({}, options.headers || {});
if (options.body != null) headers["Content-Type"] = "application/json";
var res = await window.fetch(
window.location.origin + "/api" + path,
Object.assign({ credentials: "include" }, options, { headers: headers })
);
var data = await res.json().catch(function () { return {}; });
if (!res.ok) {
var err = new Error(data.error || "HTTP " + res.status);
err.code = data.code;
err.status = res.status;
err.data = data;
throw err;
}
return data;
}
return { COLORS: COLORS, FONT: FONT, SPACE: SPACE, RADIUS: RADIUS, makeUI: makeUI, apiFetch: apiFetch };
})();