perf: move date filtering to backend to massively reduce payload size and implement smart polling for instant updates without lag
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 54s

This commit is contained in:
Cauê Faleiros
2026-05-20 11:39:14 -03:00
parent cdcbfd2622
commit 4a7ff31898
3 changed files with 89 additions and 13 deletions

View File

@@ -92,11 +92,37 @@ const formatRow = (row) => ({
ID_Pedido: row.pedido_id
});
const parseOrderDate = (dateStr) => {
if (!dateStr) return new Date(0);
if (dateStr.includes('T')) return new Date(dateStr);
const parts = dateStr.split(/[-/]/);
if (parts.length === 3) {
if (parts[0].length === 4) {
return new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));
} else {
return new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
}
}
const fallback = new Date(dateStr);
return isNaN(fallback.getTime()) ? new Date(0) : fallback;
};
// GET data (for the frontend)
app.get('/api/data', verifyToken, async (req, res) => {
try {
const result = await pool.query('SELECT * FROM orders ORDER BY id DESC');
const formattedData = result.rows.map(formatRow);
let rows = result.rows;
if (req.query.start && req.query.end) {
const startDate = new Date(req.query.start);
const endDate = new Date(req.query.end);
rows = rows.filter(row => {
const orderDate = parseOrderDate(row.data_pedido);
return orderDate >= startDate && orderDate <= endDate;
});
}
const formattedData = rows.map(formatRow);
res.json(formattedData);
} catch (error) {
console.error("Error fetching data:", error);
@@ -104,6 +130,16 @@ app.get('/api/data', verifyToken, async (req, res) => {
}
});
// Smart Polling endpoint to check for updates instantly
app.get('/api/last-update', verifyToken, async (req, res) => {
try {
const result = await pool.query('SELECT MAX(id) as max_id FROM orders');
res.json({ max_id: result.rows[0].max_id || 0 });
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
}
});
// POST data (for n8n) - Protected by API_KEY internally or via middleware if needed
// Leaving it as it was, checking API_KEY manually? Wait, the previous version didn't actually use 'authenticate' middleware on the POST!
// Let's add the authenticate middleware to the POST endpoint.