232 lines
7.9 KiB
JavaScript
232 lines
7.9 KiB
JavaScript
"use strict";
|
|
/**
|
|
* Mini-serveur sans dépendance :
|
|
* - sert les fichiers du dossier public/
|
|
* - garde la to-do list partagée dans un fichier JSON
|
|
* - diffuse chaque changement en direct à tous les appareils connectés (SSE)
|
|
*/
|
|
const http = require("http");
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
const crypto = require("crypto");
|
|
|
|
const PORT = Number(process.env.PORT) || 3000;
|
|
const PUBLIC_DIR = path.join(__dirname, "public");
|
|
const DATA_FILE = process.env.DATA_FILE || path.join(__dirname, "data", "todos.json");
|
|
const MAX_ITEMS = 500;
|
|
const MAX_TEXT = 200;
|
|
const MAX_BODY = 10 * 1024;
|
|
|
|
const MIME = {
|
|
".html": "text/html; charset=utf-8",
|
|
".css": "text/css; charset=utf-8",
|
|
".js": "text/javascript; charset=utf-8",
|
|
".json": "application/json; charset=utf-8",
|
|
".svg": "image/svg+xml",
|
|
".png": "image/png",
|
|
".ico": "image/x-icon",
|
|
".webmanifest": "application/manifest+json",
|
|
};
|
|
|
|
// ---------- Données ----------
|
|
function charger() {
|
|
try {
|
|
const liste = JSON.parse(fs.readFileSync(DATA_FILE, "utf8"));
|
|
return Array.isArray(liste) ? liste : [];
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
let todos = charger();
|
|
|
|
function sauvegarder() {
|
|
fs.mkdirSync(path.dirname(DATA_FILE), { recursive: true });
|
|
const tmp = DATA_FILE + ".tmp";
|
|
fs.writeFileSync(tmp, JSON.stringify(todos));
|
|
fs.renameSync(tmp, DATA_FILE); // écriture atomique
|
|
}
|
|
|
|
// ---------- Temps réel (Server-Sent Events) ----------
|
|
const clients = new Set();
|
|
|
|
function diffuser() {
|
|
const message = `data: ${JSON.stringify(todos)}\n\n`;
|
|
for (const res of clients) res.write(message);
|
|
}
|
|
|
|
// Un signe de vie régulier empêche les proxys de couper la connexion
|
|
setInterval(() => {
|
|
for (const res of clients) res.write(": ping\n\n");
|
|
}, 25000);
|
|
|
|
// ---------- Utilitaires HTTP ----------
|
|
function envoyerJson(res, statut, donnees) {
|
|
res.writeHead(statut, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
res.end(JSON.stringify(donnees));
|
|
}
|
|
|
|
function lireJson(req) {
|
|
return new Promise((resolve, reject) => {
|
|
let taille = 0;
|
|
const morceaux = [];
|
|
req.on("data", (morceau) => {
|
|
taille += morceau.length;
|
|
if (taille > MAX_BODY) {
|
|
reject(new Error("Requête trop volumineuse"));
|
|
req.destroy();
|
|
return;
|
|
}
|
|
morceaux.push(morceau);
|
|
});
|
|
req.on("end", () => {
|
|
try {
|
|
resolve(morceaux.length ? JSON.parse(Buffer.concat(morceaux).toString("utf8")) : {});
|
|
} catch {
|
|
reject(new Error("JSON invalide"));
|
|
}
|
|
});
|
|
req.on("error", reject);
|
|
});
|
|
}
|
|
|
|
const nettoyerTexte = (valeur) => String(valeur ?? "").replace(/\s+/g, " ").trim().slice(0, MAX_TEXT);
|
|
|
|
// ---------- API ----------
|
|
async function api(req, res, url) {
|
|
const [, ressource, id, action] = url.pathname.split("/").filter(Boolean); // /api/<ressource>/<id>/<action>
|
|
|
|
if (ressource === "events" && req.method === "GET") {
|
|
res.writeHead(200, {
|
|
"Content-Type": "text/event-stream",
|
|
"Cache-Control": "no-cache, no-transform",
|
|
Connection: "keep-alive",
|
|
"X-Accel-Buffering": "no",
|
|
});
|
|
res.write("retry: 3000\n\n");
|
|
res.write(`data: ${JSON.stringify(todos)}\n\n`);
|
|
clients.add(res);
|
|
req.on("close", () => clients.delete(res));
|
|
return;
|
|
}
|
|
|
|
if (ressource !== "todos") return envoyerJson(res, 404, { erreur: "Introuvable" });
|
|
|
|
// GET /api/todos
|
|
if (!id && req.method === "GET") return envoyerJson(res, 200, todos);
|
|
|
|
// POST /api/todos { text }
|
|
if (!id && req.method === "POST") {
|
|
const corps = await lireJson(req);
|
|
const text = nettoyerTexte(corps.text);
|
|
if (!text) return envoyerJson(res, 400, { erreur: "Texte vide" });
|
|
if (todos.length >= MAX_ITEMS) return envoyerJson(res, 400, { erreur: "Liste pleine" });
|
|
const tache = { id: crypto.randomUUID(), text, done: false, createdAt: Date.now() };
|
|
todos.push(tache);
|
|
sauvegarder();
|
|
diffuser();
|
|
return envoyerJson(res, 201, tache);
|
|
}
|
|
|
|
// POST /api/todos/clear-done : supprime toutes les tâches cochées
|
|
if (id === "clear-done" && req.method === "POST") {
|
|
todos = todos.filter((t) => !t.done);
|
|
sauvegarder();
|
|
diffuser();
|
|
return envoyerJson(res, 200, todos);
|
|
}
|
|
|
|
// POST /api/todos/:id/move { beforeId } : place la tâche juste avant beforeId (ou à la fin si null)
|
|
// Un déplacement = une seule tâche qui bouge : pas de conflit si quelqu'un d'autre modifie la liste en même temps
|
|
if (id && action === "move" && req.method === "POST") {
|
|
const corps = await lireJson(req);
|
|
const index = todos.findIndex((t) => t.id === id);
|
|
if (index === -1) return envoyerJson(res, 404, { erreur: "Tâche introuvable" });
|
|
const [tache] = todos.splice(index, 1);
|
|
const cible = typeof corps.beforeId === "string" ? todos.findIndex((t) => t.id === corps.beforeId) : -1;
|
|
if (cible === -1) todos.push(tache);
|
|
else todos.splice(cible, 0, tache);
|
|
sauvegarder();
|
|
diffuser();
|
|
return envoyerJson(res, 200, todos);
|
|
}
|
|
|
|
if (action) return envoyerJson(res, 404, { erreur: "Introuvable" });
|
|
|
|
// PATCH /api/todos/:id { done?, text? }
|
|
if (id && req.method === "PATCH") {
|
|
const tache = todos.find((t) => t.id === id);
|
|
if (!tache) return envoyerJson(res, 404, { erreur: "Tâche introuvable" });
|
|
const corps = await lireJson(req);
|
|
if (typeof corps.done === "boolean") tache.done = corps.done;
|
|
if (typeof corps.text === "string" && nettoyerTexte(corps.text)) tache.text = nettoyerTexte(corps.text);
|
|
sauvegarder();
|
|
diffuser();
|
|
return envoyerJson(res, 200, tache);
|
|
}
|
|
|
|
// DELETE /api/todos/:id
|
|
if (id && req.method === "DELETE") {
|
|
const avant = todos.length;
|
|
todos = todos.filter((t) => t.id !== id);
|
|
if (todos.length === avant) return envoyerJson(res, 404, { erreur: "Tâche introuvable" });
|
|
sauvegarder();
|
|
diffuser();
|
|
return envoyerJson(res, 200, { ok: true });
|
|
}
|
|
|
|
return envoyerJson(res, 405, { erreur: "Méthode non autorisée" });
|
|
}
|
|
|
|
// ---------- Fichiers statiques ----------
|
|
function statique(req, res, url) {
|
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
res.writeHead(405);
|
|
return res.end();
|
|
}
|
|
|
|
let relatif;
|
|
try {
|
|
relatif = decodeURIComponent(url.pathname);
|
|
} catch {
|
|
res.writeHead(400);
|
|
return res.end();
|
|
}
|
|
if (relatif.endsWith("/")) relatif += "index.html";
|
|
|
|
const fichier = path.normalize(path.join(PUBLIC_DIR, relatif));
|
|
if (!fichier.startsWith(PUBLIC_DIR + path.sep)) {
|
|
res.writeHead(403);
|
|
return res.end();
|
|
}
|
|
|
|
fs.readFile(fichier, (erreur, contenu) => {
|
|
if (erreur) {
|
|
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
|
return res.end("Page introuvable");
|
|
}
|
|
res.writeHead(200, {
|
|
"Content-Type": MIME[path.extname(fichier).toLowerCase()] || "application/octet-stream",
|
|
"Cache-Control": "no-cache",
|
|
});
|
|
res.end(req.method === "HEAD" ? undefined : contenu);
|
|
});
|
|
}
|
|
|
|
// ---------- Serveur ----------
|
|
const serveur = http.createServer(async (req, res) => {
|
|
try {
|
|
const url = new URL(req.url, "http://localhost");
|
|
if (url.pathname === "/healthz") return envoyerJson(res, 200, { ok: true });
|
|
if (url.pathname.startsWith("/api/")) return await api(req, res, url);
|
|
return statique(req, res, url);
|
|
} catch (erreur) {
|
|
if (!res.headersSent) envoyerJson(res, 400, { erreur: erreur.message });
|
|
else res.end();
|
|
}
|
|
});
|
|
|
|
serveur.listen(PORT, "0.0.0.0", () => {
|
|
console.log(`Serveur démarré sur le port ${PORT} (données : ${DATA_FILE})`);
|
|
});
|