separado en routes

This commit is contained in:
Lucas Tettamanti
2026-01-14 13:03:11 -03:00
parent 2d01972619
commit 47ba68049f
4 changed files with 108 additions and 69 deletions

View File

@@ -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);

32
src/app.js Normal file
View File

@@ -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;
}

13
src/routes/evolution.js Normal file
View File

@@ -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;
}

61
src/routes/simulator.js Normal file
View File

@@ -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;
}