From 47ba68049f58d51d81edb4fb309fac1909297902 Mon Sep 17 00:00:00 2001 From: Lucas Tettamanti <757326+lkzwieder@users.noreply.github.com> Date: Wed, 14 Jan 2026 13:03:11 -0300 Subject: [PATCH] separado en routes --- index.js | 71 ++--------------------------------------- src/app.js | 32 +++++++++++++++++++ src/routes/evolution.js | 13 ++++++++ src/routes/simulator.js | 61 +++++++++++++++++++++++++++++++++++ 4 files changed, 108 insertions(+), 69 deletions(-) create mode 100644 src/app.js create mode 100644 src/routes/evolution.js create mode 100644 src/routes/simulator.js diff --git a/index.js b/index.js index eec1b4a..c7e73b1 100644 --- a/index.js +++ b/index.js @@ -1,18 +1,6 @@ import "dotenv/config"; -import express from "express"; -import cors from "cors"; -import path from "path"; -import { fileURLToPath } from "url"; import { ensureTenant } from "./src/db/repo.js"; -import { addSseClient, removeSseClient } from "./src/services/sse.js"; -import { makeGetConversations } from "./src/controllers/conversations.js"; -import { makeListRuns, makeGetRunById } from "./src/controllers/runs.js"; -import { makeSimSend } from "./src/controllers/sim.js"; -import { makeEvolutionWebhook } from "./src/controllers/evolution.js"; -import { makeGetConversationState } from "./src/controllers/conversationState.js"; -import { makeListMessages } from "./src/controllers/messages.js"; -import { makeSearchProducts } from "./src/controllers/products.js"; -import { makeDeleteConversation, makeDeleteUser, makeListUsers, makeRetryLast } from "./src/controllers/admin.js"; +import { createApp } from "./src/app.js"; async function configureUndiciDispatcher() { // Node 18+ usa undici debajo de fetch. Esto suele arreglar timeouts “fantasma” por keep-alive/pooling. @@ -33,68 +21,12 @@ async function configureUndiciDispatcher() { } } -const app = express(); -app.use(cors()); -app.use(express.json({ limit: "1mb" })); - -// Serve /public as static (UI + webcomponents) -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); -const publicDir = path.join(__dirname, "public"); -app.use(express.static(publicDir)); - /** * --- Tenant --- */ const TENANT_KEY = process.env.TENANT_KEY || "piaf"; let TENANT_ID = null; -function nowIso() { - return new Date().toISOString(); -} - -/** - * --- SSE endpoint --- - */ -app.get("/stream", (req, res) => { - res.setHeader("Content-Type", "text/event-stream"); - res.setHeader("Cache-Control", "no-cache"); - res.setHeader("Connection", "keep-alive"); - res.flushHeaders?.(); - - res.write(`event: hello\ndata: ${JSON.stringify({ ts: nowIso() })}\n\n`); - addSseClient(res); - - req.on("close", () => { - removeSseClient(res); - res.end(); - }); -}); - -/** - * --- UI data endpoints --- - */ -app.post("/sim/send", makeSimSend()); - -app.get("/conversations", makeGetConversations(() => TENANT_ID)); -app.get("/conversations/state", makeGetConversationState(() => TENANT_ID)); -app.delete("/conversations/:chat_id", makeDeleteConversation(() => TENANT_ID)); -app.post("/conversations/:chat_id/retry-last", makeRetryLast(() => TENANT_ID)); -app.get("/messages", makeListMessages(() => TENANT_ID)); -app.get("/products", makeSearchProducts(() => TENANT_ID)); -app.get("/users", makeListUsers(() => TENANT_ID)); -app.delete("/users/:chat_id", makeDeleteUser(() => TENANT_ID)); - -app.get("/runs", makeListRuns(() => TENANT_ID)); - -app.get("/runs/:run_id", makeGetRunById(() => TENANT_ID)); - -app.post("/webhook/evolution", makeEvolutionWebhook()); - -app.get("/", (req, res) => { - res.sendFile(path.join(publicDir, "index.html")); -}); - /** * --- Boot --- */ @@ -103,6 +35,7 @@ const port = process.env.PORT || 3000; (async function boot() { await configureUndiciDispatcher(); TENANT_ID = await ensureTenant({ key: TENANT_KEY, name: TENANT_KEY.toUpperCase() }); + const app = createApp({ tenantId: TENANT_ID }); app.listen(port, () => console.log(`UI: http://localhost:${port} (tenant=${TENANT_KEY})`)); })().catch((err) => { console.error("Boot failed:", err); diff --git a/src/app.js b/src/app.js new file mode 100644 index 0000000..f6c7cc0 --- /dev/null +++ b/src/app.js @@ -0,0 +1,32 @@ +import express from "express"; +import cors from "cors"; +import path from "path"; +import { fileURLToPath } from "url"; + +import { createSimulatorRouter } from "./routes/simulator.js"; +import { createEvolutionRouter } from "./routes/evolution.js"; + +export function createApp({ tenantId }) { + const app = express(); + + app.use(cors()); + app.use(express.json({ limit: "1mb" })); + + // Serve /public as static (UI + webcomponents) + const __filename = fileURLToPath(import.meta.url); + const __dirname = path.dirname(__filename); + const publicDir = path.join(__dirname, "..", "public"); + app.use(express.static(publicDir)); + + // --- Integraciones / UI --- + app.use(createSimulatorRouter({ tenantId })); + app.use(createEvolutionRouter()); + + // Home (UI) + app.get("/", (req, res) => { + res.sendFile(path.join(publicDir, "index.html")); + }); + + return app; +} + diff --git a/src/routes/evolution.js b/src/routes/evolution.js new file mode 100644 index 0000000..feef4a7 --- /dev/null +++ b/src/routes/evolution.js @@ -0,0 +1,13 @@ +import express from "express"; +import { makeEvolutionWebhook } from "../controllers/evolution.js"; + +/** + * Integración Evolution (webhook). + * Mantiene exactamente el mismo path que existía en `index.js`. + */ +export function createEvolutionRouter() { + const router = express.Router(); + router.post("/webhook/evolution", makeEvolutionWebhook()); + return router; +} + diff --git a/src/routes/simulator.js b/src/routes/simulator.js new file mode 100644 index 0000000..29d9379 --- /dev/null +++ b/src/routes/simulator.js @@ -0,0 +1,61 @@ +import express from "express"; + +import { addSseClient, removeSseClient } from "../services/sse.js"; +import { makeGetConversations } from "../controllers/conversations.js"; +import { makeListRuns, makeGetRunById } from "../controllers/runs.js"; +import { makeSimSend } from "../controllers/sim.js"; +import { makeGetConversationState } from "../controllers/conversationState.js"; +import { makeListMessages } from "../controllers/messages.js"; +import { makeSearchProducts } from "../controllers/products.js"; +import { makeDeleteConversation, makeDeleteUser, makeListUsers, makeRetryLast } from "../controllers/admin.js"; + +function nowIso() { + return new Date().toISOString(); +} + +/** + * Endpoints consumidos por el frontend (UI / simulador). + * Mantiene exactamente los mismos paths que existían en `index.js`. + */ +export function createSimulatorRouter({ tenantId }) { + const router = express.Router(); + const getTenantId = () => tenantId; + + /** + * --- SSE endpoint --- + */ + router.get("/stream", (req, res) => { + res.setHeader("Content-Type", "text/event-stream"); + res.setHeader("Cache-Control", "no-cache"); + res.setHeader("Connection", "keep-alive"); + res.flushHeaders?.(); + + res.write(`event: hello\ndata: ${JSON.stringify({ ts: nowIso() })}\n\n`); + addSseClient(res); + + req.on("close", () => { + removeSseClient(res); + res.end(); + }); + }); + + /** + * --- UI data endpoints --- + */ + router.post("/sim/send", makeSimSend()); + + router.get("/conversations", makeGetConversations(getTenantId)); + router.get("/conversations/state", makeGetConversationState(getTenantId)); + router.delete("/conversations/:chat_id", makeDeleteConversation(getTenantId)); + router.post("/conversations/:chat_id/retry-last", makeRetryLast(getTenantId)); + router.get("/messages", makeListMessages(getTenantId)); + router.get("/products", makeSearchProducts(getTenantId)); + router.get("/users", makeListUsers(getTenantId)); + router.delete("/users/:chat_id", makeDeleteUser(getTenantId)); + + router.get("/runs", makeListRuns(getTenantId)); + router.get("/runs/:run_id", makeGetRunById(getTenantId)); + + return router; +} +