Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 14 additions & 25 deletions backend/src/routes/notes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,37 +318,26 @@ router.get('/', async (req: AuthRequest, res: Response, next) => {
sql += ` ORDER BY pinned DESC, updated_at DESC LIMIT $${paramCount + 1} OFFSET $${paramCount + 2}`;
params.push(limit, offset);

// Contar total
let countResult: { total: string }[];
// ⚑ OPTIMIZATION: Execute COUNT and SELECT in parallel
// This reduces latency by running independent queries concurrently
let total = 0;
let notes: unknown[] = [];

try {
countResult = await query(countSql, countParams) as { total: string }[];
const [countResultRaw, queryResult] = await Promise.all([
query(countSql, countParams) as Promise<{ total: string }[]>,
query(sql, params) as Promise<unknown[] | { rows: unknown[] }>
]);

const countResult = countResultRaw;
total = parseInt(countResult?.[0]?.total || '0', 10);
} catch (countError) {
console.error('[Notes GET] ❌ Erro ao contar notas:', {
error: (countError as Error)?.message,
sql: countSql,
params: countParams,
stack: (countError as Error)?.stack?.substring(0, 300)
});
// βœ… FIX: Retornar erro mais descritivo ao invΓ©s de lanΓ§ar
console.error('[Notes GET] ❌ Erro fatal ao contar notas:', countError);
return sendError(res, 'Erro ao contar notas', 500, 'COUNT_ERROR');
}
notes = Array.isArray(queryResult) ? queryResult : ((queryResult as any)?.rows || []);

// Buscar notas paginadas
let notes: unknown[];
try {
const queryResult = await query(sql, params);
notes = Array.isArray(queryResult) ? queryResult : (queryResult?.rows || []);
} catch (queryError) {
} catch (error) {
console.error('[Notes GET] ❌ Erro ao buscar notas:', {
error: (queryError as Error)?.message,
sql: sql.substring(0, 200),
paramsCount: params.length,
stack: (queryError as Error)?.stack?.substring(0, 300)
error: (error as Error)?.message,
stack: (error as Error)?.stack?.substring(0, 300)
});
// βœ… FIX: Retornar erro mais descritivo
return sendError(res, 'Erro ao buscar notas', 500, 'QUERY_ERROR');
}

Expand Down
118 changes: 118 additions & 0 deletions backend/src/tests/routes/notes-benchmark.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import request from "supertest";
import express from "express";
import { jest } from "@jest/globals";

// Mock middleware
const mockAuth = (req: any, res: any, next: any) => {
req.userId = "test-user-id";
next();
};

const mockValidateId = (paramName: string) => (req: any, res: any, next: any) => {
next();
};

// Mock database with delay
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

jest.mock("../../../src/services/database.js", () => ({
query: jest.fn(async (sql: string, params: any[]) => {
await sleep(50); // Simulate 50ms DB latency
if (sql.includes("COUNT(*)")) {
return [{ total: "10" }];
}
if (sql.includes("SELECT")) {
// Simulate notes list
return Array(10).fill({
id: "note-id",
title: "Test Note",
content: "Content",
tags: [],
category: "general",
pinned: false,
archived: false,
attachments: [],
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
});
}
return [];
}),
queryOne: jest.fn(),
transaction: jest.fn(),
}));

jest.mock("../../../src/middleware/auth.js", () => ({
authenticateToken: mockAuth,
}));

jest.mock("../../../src/middleware/validateId.js", () => ({
validateIdParam: mockValidateId,
}));

jest.mock("../../../src/services/embeddings.js", () => ({
generateEmbedding: jest.fn().mockResolvedValue(Array(768).fill(0)),
}));

jest.mock("../../../src/services/storage.service.js", () => ({
storageService: {
isReady: jest.fn().mockReturnValue(true),
uploadFile: jest.fn(),
deleteFile: jest.fn(),
}
}));

jest.mock("../../../src/services/supermemory/supermemory.service.js", () => ({
supermemoryService: {
saveMemory: jest.fn(),
}
}));

jest.mock("../../../src/services/document-processor.service.js", () => ({
documentProcessorService: {
extractTextFromFile: jest.fn(),
}
}));

jest.mock("../../../src/services/langchain/agents/notes-agent.js", () => ({
getNotesAgent: jest.fn(),
NOTES_AI_HELPER_AGENTS: [],
}));


// Import routes AFTER mocking dependencies
import { notesRoutes } from "../../../src/routes/notes.js";

const app = express();
app.use(express.json());
app.use("/api/notes", notesRoutes);

describe("Notes API Performance", () => {
beforeEach(() => {
jest.clearAllMocks();
});

describe("GET /api/notes", () => {
it("should measure execution time of list notes", async () => {
const start = Date.now();
const res = await request(app).get("/api/notes");
const duration = Date.now() - start;

expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
// Depending on pagination response structure
// pagination response usually is { data: [], pagination: {}, success: true }
// or simply returning data array if not properly wrapped
// Check implementation: sendSuccess(res, paginatedResponse.data, 200, { pagination: ... }) or sendPaginated(res, normalizedNotes, ...)
// Assuming sendSuccess returns { success: true, data: [...], pagination: ... }

console.log(`GET /api/notes duration: ${duration}ms`);

// Without optimization (sequential): 50ms (count) + 50ms (select) = ~100ms
// With optimization (parallel): max(50ms, 50ms) = ~50ms

// We expect the duration to be roughly >= 100ms currently.
// But we will optimize it to be around 50ms.
});
});
});
Loading