diff --git a/backend/src/routes/projects.ts b/backend/src/routes/projects.ts index adf8efb5..95a0b8d3 100644 --- a/backend/src/routes/projects.ts +++ b/backend/src/routes/projects.ts @@ -252,16 +252,6 @@ router.get('/:id/tasks', validateIdParam('id'), async (req: AuthRequest, res, ne const { status } = req.query; const offset = calculateOffset(page, limit); - // Verificar se projeto existe e pertence ao usuário - const project = await queryOne( - 'SELECT id FROM projects WHERE id = $1 AND user_id = $2', - [id, req.userId] - ); - - if (!project) { - return res.status(404).json({ error: 'Projeto não encontrado' }); - } - let whereClause = 'WHERE user_id = $1 AND project_id = $2'; const params: (string | number)[] = [req.userId!, id]; let paramIndex = 3; @@ -272,21 +262,32 @@ router.get('/:id/tasks', validateIdParam('id'), async (req: AuthRequest, res, ne paramIndex++; } - const countResult = await query( - `SELECT COUNT(*) as total FROM tasks ${whereClause}`, - params - ) as { total: string }[]; - const total = parseInt(countResult?.[0]?.total || '0'); - const allowedSortFields = ['created_at', 'updated_at', 'due_date', 'priority', 'title']; const safeSortBy = allowedSortFields.includes(sortBy as string) ? sortBy as string : 'created_at'; - const tasks = await query( - `SELECT * FROM tasks ${whereClause} + // ⚡ Performance Optimization: Execute all queries concurrently + const [project, countResult, tasks] = await Promise.all([ + queryOne( + 'SELECT id FROM projects WHERE id = $1 AND user_id = $2', + [id, req.userId] + ), + query( + `SELECT COUNT(*) as total FROM tasks ${whereClause}`, + params + ) as Promise<{ total: string }[]>, + query( + `SELECT * FROM tasks ${whereClause} ORDER BY ${safeSortBy} ${order}, created_at DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, - [...params, limit, offset] - ); + [...params, limit, offset] + ) + ]); + + if (!project) { + return res.status(404).json({ error: 'Projeto não encontrado' }); + } + + const total = parseInt(countResult?.[0]?.total || '0'); res.json(buildPaginatedResponse(tasks || [], total, { page, limit, sortBy, order })); } catch (error: unknown) {