Volver a la wiki

Endpoints Chat — /api/chat/ (CF Pages Functions)

Resumen

Conjunto de tres CF Pages Functions que implementan el backend del Team Chat (s69). Persisten datos en D1 (chat_messages, chat_typing). No requieren sesión Django — la autenticación externa la provee CF Access + middleware del workspace.


Endpoints

GET /api/chat/messages

Devuelve mensajes ordenados cronológicamente (ASC).

ParamTipoDefaultDescripción
limitint100Máx mensajes a devolver (cap 500)
beforeISO string—Paginación: mensajes con created_at < before

Respuesta 200:

[
  { "id": 42, "author": "Edu", "body": "...", "created_at": "2026-05-18 13:10:00" },
  ...
]

La query interna usa ORDER BY DESC + cap, luego invierte a ASC antes de serializar.


POST /api/chat/messages

Crea un nuevo mensaje.

Body:

{ "author": "Txell", "body": "Texto del mensaje" }
ValidaciónCódigo
author o body vacíos400
author no en allowlist400
Error D1 insert500

Respuesta 201: el mensaje creado tal como queda en DB (con id real e created_at definitivo).

El frontend usa Optimistic UI: inserta con id negativo temporal y lo sustituye al recibir el 201. Si recibe error, hace rollback.


DELETE /api/chat/messages/{messageId}?author=X

Borra un mensaje. Solo el autor puede borrar el suyo.

PasoDescripción
1Lee ?author del query param
2Consulta SELECT author FROM chat_messages WHERE id = ?
3Compara msg.author !== claimedAuthor → 403 si no coincide
4Ejecuta DELETE

Respuestas: 204 éxito · 400 sin author param · 403 no es el autor · 404 mensaje no existe · 500 error D1.


GET /api/chat/typing

Devuelve array de nombres de autores con typing activo (last_typed_at dentro de los últimos 5 s).

["Dani"]

POST /api/chat/typing

Refresca el last_typed_at del autor (upsert). El frontend lo llama throttled cada 3 s mientras el usuario teclea.

Body: { "author": "Edu" }

Respuesta: 204 · 400 si author inválido.

SQL: INSERT … ON CONFLICT(author) DO UPDATE SET last_typed_at = datetime('now')


Seguridad


Esquema D1

CREATE TABLE chat_messages (
  id         INTEGER PRIMARY KEY AUTOINCREMENT,
  author     TEXT NOT NULL,          -- Edu | Dani | Txell
  body       TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX idx_chat_messages_created_at ON chat_messages(created_at DESC);

CREATE TABLE chat_typing (
  author       TEXT PRIMARY KEY,     -- Edu | Dani | Txell
  last_typed_at TEXT NOT NULL DEFAULT (datetime('now'))
);

Migración: migrations/0030_create_chat.sql — aplicada en remote D1 el 18-05-2026.


Véase también

Subir