From ac6b5bacb7a69349ec884a3ad79ccaabc1ad7b1e Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Tue, 7 Apr 2026 17:33:10 +0000 Subject: [PATCH] refactor(backend): optimize backend snippets for deterministic Agent parsing Co-authored-by: beginwebdev2002 <102213457+beginwebdev2002@users.noreply.github.com> --- backend/expressjs/readme.md | 60 +++++++++++----------- backend/mongodb/database-optimization.md | 6 +-- backend/mongodb/readme.md | 2 +- backend/mongodb/security-best-practices.md | 6 +-- backend/nestjs/readme.md | 60 +++++++++++----------- backend/nodejs/readme.md | 20 ++++---- backend/readme.md | 2 +- 7 files changed, 78 insertions(+), 78 deletions(-) diff --git a/backend/expressjs/readme.md b/backend/expressjs/readme.md index 937e8eb..c292f11 100644 --- a/backend/expressjs/readme.md +++ b/backend/expressjs/readme.md @@ -65,7 +65,7 @@ app.post('/api/users', async (req, res) => { }); ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Placing database connections, routing, and business logic into a single monolithic file tightly couples dependencies and violates the Single Responsibility Principle. This makes the codebase impossible to scale, unit test, or safely extend. ### ✅ Best Practice ```javascript router.post('/api/users', UserController.create); @@ -83,7 +83,7 @@ class UserController { router.get('/', async (req, res) => { throw new Error('Crash'); }); // Express 4 не ловит rejection ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Uncaught promise rejections in Express 4 route handlers bypass the global error middleware, causing the request to hang indefinitely. This leads to connection timeouts, memory leaks, and poor client experience. ### ✅ Best Practice ```javascript const asyncHandler = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); @@ -98,7 +98,7 @@ router.get('/', asyncHandler(UserController.get)); app.use((req, res) => res.status(404).send('Not Found')); // Нет ловца ошибок 500 ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Handling errors locally in every controller duplicates logic and leads to inconsistent API responses. It also risks exposing sensitive internal error details (like stack traces) to the client if not caught properly. ### ✅ Best Practice ```javascript app.use((err, req, res, next) => { @@ -115,7 +115,7 @@ app.use((err, req, res, next) => { if (!req.body.email || req.body.age < 18) return res.status(400); // Ручная проверка ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Lack of strict payload validation allows malformed data to penetrate the business logic and database layers. This causes runtime exceptions, data corruption, and potential injection attacks. ### ✅ Best Practice ```javascript const validate = schema => (req, res, next) => { @@ -134,7 +134,7 @@ router.post('/', validate(userSchema), UserController.create); mongoose.connect('mongodb://admin:pass@host/db'); // Хардкод секретов ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Hardcoding configuration values or scattering `process.env` access throughout the codebase tightly couples the app to its environment. This makes testing difficult and increases the risk of deploying with incorrect configurations. ### ✅ Best Practice ```javascript require('dotenv').config(); @@ -147,7 +147,7 @@ mongoose.connect(process.env.DB_URI); ### ❌ Bad Practice // Приложение светит 'X-Powered-By: Express' ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Omitting security headers leaves the application vulnerable to common web exploits like Cross-Site Scripting (XSS), Clickjacking, and MIME-type sniffing, compromising client-side security. ### ✅ Best Practice ```javascript const helmet = require('helmet'); @@ -162,7 +162,7 @@ app.use(helmet()); app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); next(); }); ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Using a wildcard (`*`) for CORS allows any domain to make authenticated requests to the API. This exposes the application to Cross-Site Request Forgery (CSRF) and unauthorized data access. ### ✅ Best Practice ```javascript const cors = require('cors'); @@ -175,7 +175,7 @@ app.use(cors({ origin: 'https://myapp.com', credentials: true })); ### ❌ Bad Practice // API открыт для миллиона запросов в секунду ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Lacking rate limiting exposes the API to Brute Force and Denial-of-Service (DDoS) attacks. Attackers can easily exhaust server resources, take down the application, or brute-force authentication endpoints. ### ✅ Best Practice ```javascript const rateLimit = require('express-rate-limit'); @@ -190,7 +190,7 @@ app.use('/api/', rateLimit({ windowMs: 15 * 60 * 1000, max: 100 })); app.use(express.json()); // Злоумышленник может отправить 500Мб JSON ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Allowing infinitely large request bodies makes the server susceptible to memory exhaustion and Denial-of-Service (DoS) attacks, as attackers can send massive payloads that crash the process. ### ✅ Best Practice ```javascript app.use(express.json({ limit: '10kb' })); @@ -205,7 +205,7 @@ app.use(express.urlencoded({ extended: true, limit: '10kb' })); console.log('User signed in'); ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to centralize logging leaves critical audit trails scattered across isolated console outputs. This drastically impairs incident response and distributed tracing across microservices. ### ✅ Best Practice ```javascript app.use(morgan('combined', { stream: winstonLogger.stream })); @@ -220,7 +220,7 @@ winstonLogger.info('User signed in'); // Коннект к базе делается перед каждым запросом ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Re-establishing database connections on every request adds massive latency and quickly exhausts connection pools. This causes the database server to refuse new connections, bringing down the entire application. ### ✅ Best Practice ```javascript mongoose.connect(process.env.DB_URI).then(() => { @@ -236,7 +236,7 @@ mongoose.connect(process.env.DB_URI).then(() => { // Проверка токена встроена в контроллер профиля ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Embedding authentication logic directly within business controllers violates the Single Responsibility Principle. This makes the logic difficult to test, reuse, and maintain, increasing the risk of bypassing security checks. ### ✅ Best Practice ```javascript const authGuard = (req, res, next) => { @@ -255,7 +255,7 @@ const authGuard = (req, res, next) => { if (req.user.role !== 'admin') return res.status(403); ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Hardcoding role checks inside route handlers creates a fragile and inflexible authorization model. This approach is prone to errors, hard to audit, and difficult to scale as new roles are introduced. ### ✅ Best Practice ```javascript const requireRole = (...roles) => (req, res, next) => { @@ -273,7 +273,7 @@ router.delete('/:id', requireRole('admin', 'manager'), Controller.del); res.json({ foo: 'bar' }); // Каждый метод возвращает случайную структуру ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Inconsistent API response formats force clients to implement complex, error-prone parsing logic. It breaks the contract between client and server, leading to frustrating integration experiences. ### ✅ Best Practice ```javascript class ApiResponse { @@ -290,7 +290,7 @@ class ApiResponse { res.json(users); // Выбросить миллион записей ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Returning massive, unpaginated datasets consumes excessive memory and network bandwidth. This leads to severe performance bottlenecks, sluggish API response times, and potential out-of-memory crashes. ### ✅ Best Practice ```javascript const page = parseInt(req.query.page) || 1; @@ -304,7 +304,7 @@ res.json({ data: users, meta: { total, page, limit, pages: Math.ceil(total/limit ### ❌ Bad Practice // При получении SIGTERM сервер моментально обрывает процессы ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Immediate process termination severs active connections and leaves database operations in an unknown state. This causes data corruption and forces clients to experience unhandled connection drops. ### ✅ Best Practice ```javascript process.on('SIGTERM', () => { @@ -320,7 +320,7 @@ process.on('SIGTERM', () => { ### ❌ Bad Practice // Если роут не найден, возвращается пустая белая страница ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to explicitly handle unmatched routes results in inconsistent default framework responses (e.g., HTML error pages). This breaks API contracts for clients expecting structured JSON responses. ### ✅ Best Practice ```javascript app.use('*', (req, res) => { @@ -337,7 +337,7 @@ app.use('*', (req, res) => { /app.js // Монолит на 5000 строк ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +A monolithic, unstructured codebase prevents clear separation of concerns, making the system difficult to navigate, test, and scale. This drastically slows down development velocity and increases technical debt. ### ✅ Best Practice ``` src/ @@ -354,7 +354,7 @@ src/ ### ❌ Bad Practice // Нет проверки жизнеспособности подов Kubernetes ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Without a dedicated health endpoint, container orchestrators (like Kubernetes) cannot accurately determine the pod's status. This leads to traffic being routed to dead containers or premature termination of healthy ones. ### ✅ Best Practice ```javascript app.get('/health', (req, res) => { @@ -370,7 +370,7 @@ app.get('/health', (req, res) => { User.find({ username: req.body.username }); // body.username = { "$gt": "" } ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to sanitize inputs against MongoDB operators allows attackers to manipulate query logic (NoSQL Injection). This can lead to unauthorized data access, authentication bypass, or data destruction. ### ✅ Best Practice ```javascript const mongoSanitize = require('express-mongo-sanitize'); @@ -385,7 +385,7 @@ app.use(xss()); ### ❌ Bad Practice // Документация в стороннем Word-файле ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Maintaining API documentation manually outside the codebase guarantees it will become outdated and inaccurate. This severely degrades the developer experience for frontend teams and third-party integrators. ### ✅ Best Practice ```javascript const swaggerUi = require('swagger-ui-express'); @@ -401,7 +401,7 @@ app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); const UserService = require('./UserService'); // Прямой импорт, невозможно тестировать ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Hardcoding module dependencies using `require()` creates tight coupling and makes unit testing nearly impossible. It prevents swapping out real implementations with mocks, hindering test-driven development. ### ✅ Best Practice ```javascript class UserController { @@ -416,7 +416,7 @@ const controller = new UserController(new UserService(db)); ### ❌ Bad Practice // Парсинг бинарников руками ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Processing multipart/form-data manually is error-prone and inefficient. It risks memory bloat, incomplete file parsing, and exposes the server to vulnerabilities related to improperly handled binary streams. ### ✅ Best Practice ```javascript const multer = require('multer'); @@ -433,7 +433,7 @@ await emailService.send(); // Блокировка респонса res.send('Welcome'); ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Awaiting slow, non-critical tasks (like sending emails) directly in the request handler blocks the HTTP response. This unnecessarily increases API latency and degrades the user experience. ### ✅ Best Practice ```javascript const EventEmitter = require('events'); @@ -450,7 +450,7 @@ res.send('Welcome'); ### ❌ Bad Practice // БД обрабатывает сложные расчеты на каждый хит ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Recalculating expensive computations or querying the database for static data on every request creates severe performance bottlenecks. This overwhelms backend resources and limits the application's scalability. ### ✅ Best Practice ```javascript const cacheMiddleware = (req, res, next) => { @@ -469,7 +469,7 @@ const cacheMiddleware = (req, res, next) => { throw new Error('Not found'); ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Using standard `Error` objects limits the ability to programmatically categorize exceptions. It forces reliance on string matching for error handling, which is brittle and non-deterministic. ### ✅ Best Practice ```javascript class AppError extends Error { @@ -490,7 +490,7 @@ throw new AppError('User not found', 404); req.ip // Дает '127.0.0.1' через Nginx ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to configure `trust proxy` behind a reverse proxy (like Nginx) results in the application seeing the proxy's IP instead of the client's. This breaks rate limiting, logging, and geolocation logic. ### ✅ Best Practice ```javascript app.set('trust proxy', 1); // Доверяем первому прокси @@ -505,7 +505,7 @@ app.set('trust proxy', 1); // Доверяем первому прокси app.listen(3000); // Мешает интеграционным тестам ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Starting the server within the same file that defines the Express application hinders integration testing. It prevents test runners (like Supertest) from dynamically binding to ephemeral ports without conflicting with the running server. ### ✅ Best Practice ```javascript // app.js @@ -522,7 +522,7 @@ app.listen(3000); ### ❌ Bad Practice // Ошибки в логах невозможно связать с конкретным пользователем ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Without a unique request ID, tracing a specific user's journey through application logs is impossible. This severely complicates debugging and incident response in distributed or high-traffic systems. ### ✅ Best Practice ```javascript const { v4: uuidv4 } = require('uuid'); @@ -539,7 +539,7 @@ app.use((req, res, next) => { ### ❌ Bad Practice // Сессия хранится в памяти (MemoryStore) с открытыми куками ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Storing sessions in memory causes memory leaks and prevents horizontal scaling, as sessions are not shared across instances. Additionally, exposing unencrypted cookies allows session hijacking. ### ✅ Best Practice ```javascript app.use(session({ diff --git a/backend/mongodb/database-optimization.md b/backend/mongodb/database-optimization.md index 575c9f2..8e5d14e 100644 --- a/backend/mongodb/database-optimization.md +++ b/backend/mongodb/database-optimization.md @@ -43,7 +43,7 @@ db.orders.createIndex({ status: 1, date: 1, amount: 1 }) ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `the architectural pattern` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. --- ## 🏗️ 2. Aggregation Pipeline Optimization @@ -77,7 +77,7 @@ db.users.aggregate([ ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `the architectural pattern` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. --- ## 📉 3. Covered Queries @@ -101,7 +101,7 @@ db.orders.find( ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `the architectural pattern` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. ### ✅ Best Practice diff --git a/backend/mongodb/readme.md b/backend/mongodb/readme.md index 01aecad..cb32d67 100644 --- a/backend/mongodb/readme.md +++ b/backend/mongodb/readme.md @@ -42,7 +42,7 @@ For deep dives into specific topics, consult the specialized guides: db.users.insertOne({ name: "John", age: -5, admin: true }); ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `schema validation` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice Implement strict schema validation using JSON Schema in MongoDB. #### 🚀 Solution diff --git a/backend/mongodb/security-best-practices.md b/backend/mongodb/security-best-practices.md index 4e98a5d..c5b477b 100644 --- a/backend/mongodb/security-best-practices.md +++ b/backend/mongodb/security-best-practices.md @@ -50,7 +50,7 @@ db.createUser({ ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `the architectural pattern` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. --- ## 🔐 2. NoSQL Injection Prevention @@ -91,7 +91,7 @@ const user = await db.collection('users').findOne({ ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `the architectural pattern` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. --- ## 🗄️ 3. Encryption at Rest @@ -110,7 +110,7 @@ Enable WiredTiger encryption at rest using a robust Key Management Service (KMS) ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `the architectural pattern` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. ### 🚀 Solution diff --git a/backend/nestjs/readme.md b/backend/nestjs/readme.md index f2958a6..524e90b 100644 --- a/backend/nestjs/readme.md +++ b/backend/nestjs/readme.md @@ -65,7 +65,7 @@ export class UsersService { } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `clean architecture modules (изоляция логики)` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript @Injectable() @@ -85,7 +85,7 @@ create(@Body() dto: CreateUserDto) { } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `global validationpipe` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript // main.ts @@ -101,7 +101,7 @@ app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: t create(@Body() body: unknown) {} // Потеря типизации ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `data transfer objects (dto)` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript export class CreateUserDto { @@ -124,7 +124,7 @@ async createUser(@Body() dto: CreateDto) { } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `fat controllers vs thin controllers` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript @Post() @@ -141,7 +141,7 @@ async createUser(@Body() dto: CreateDto) { try { ... } catch (e) { throw new HttpException('Error', 500); } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `global exception filter` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript @Catch() @@ -160,7 +160,7 @@ app.useGlobalFilters(new AllExceptionsFilter()); TypeOrmModule.forRoot({ url: process.env.DB_URL }) // Переменные могут быть еще не загружены ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `async module configuration` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript TypeOrmModule.forRootAsync({ @@ -178,7 +178,7 @@ TypeOrmModule.forRootAsync({ const secret = process.env.JWT_SECRET; // Прямой вызов ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `configuration management` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript constructor(private configService: ConfigService) {} @@ -194,7 +194,7 @@ const secret = this.configService.get('JWT_SECRET'); getProfile(@Req() req: Request) { return req.user; } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `custom decorators (извлечение user)` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript export const CurrentUser = createParamDecorator((data, ctx: ExecutionContext) => ctx.switchToHttp().getRequest().user); @@ -212,7 +212,7 @@ getProfile(@CurrentUser() user: UserEntity) { return user; } getData(@Req() req) { if (!req.headers.auth) throw new UnauthorizedException(); } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `jwt guards (защита роутов)` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript @UseGuards(JwtAuthGuard) @@ -229,7 +229,7 @@ getData() {} getAdminData(@CurrentUser() user) { if (user.role !== 'ADMIN') throw new ForbiddenException(); } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `role-based access control (rbac)` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript @Roles('ADMIN') @@ -247,7 +247,7 @@ getAdminData() {} getUser(@Param('id') id: string) { const userId = parseInt(id, 10); } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `built-in pipes for transformation` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript @Get(':id') @@ -262,7 +262,7 @@ getUser(@Param('id', ParseIntPipe) id: number) {} return { success: true, data: result, timestamp: new Date() }; // Дублирование везде ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `response interceptors (трансформация ответа)` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript @Injectable() @@ -280,7 +280,7 @@ export class TransformInterceptor implements NestInterceptor { getData() { console.log('Request started'); /* ... */ console.log('Done'); } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `logging interceptors` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript @Injectable() @@ -300,7 +300,7 @@ export class LoggingInterceptor implements NestInterceptor { await this.repo1.save(data1); await this.repo2.save(data2); // Нет транзакции ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `transaction handling (typeorm)` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript await this.dataSource.transaction(async manager => { @@ -318,7 +318,7 @@ await this.dataSource.transaction(async manager => { export class CreateDogDto { name: string; } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Maintaining API documentation manually outside the codebase guarantees it will become outdated and inaccurate. This severely degrades the developer experience for frontend teams and third-party integrators. #### ✅ Best Practice ```typescript export class CreateDogDto { @@ -333,7 +333,7 @@ export class CreateDogDto { #### ❌ Bad Practice // Нет защиты от DDoS и брутфорса #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to follow best practices for `rate limiting (throttlermodule)` tightly couples dependencies and degrades predictability. This unstructured approach deviates from deterministic AI-coding standards, creating severe architectural debt and potential security vulnerabilities in enterprise scaling. #### ✅ Best Practice ```typescript // app.module.ts @@ -346,7 +346,7 @@ ThrottlerModule.forRoot([{ ttl: 60000, limit: 10 }]) #### ❌ Bad Practice // Каждый запрос делает тяжелый расчет в БД #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Executing computationally expensive operations or querying the database for static data on every request creates severe performance bottlenecks. It needlessly wastes database resources and degrades overall system throughput. #### ✅ Best Practice ```typescript @UseInterceptors(CacheInterceptor) @@ -364,7 +364,7 @@ await this.userService.create(); await this.emailService.send(); // Жесткая привязка зависимостей ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Synchronously calling unrelated services (e.g., sending an email after user creation) creates tight coupling and increases request latency. This violates event-driven architecture principles, making the system less resilient to partial failures. #### ✅ Best Practice ```typescript await this.userService.create(); @@ -379,7 +379,7 @@ this.eventEmitter.emit('user.created', new UserCreatedEvent(user)); setInterval(() => this.cleanupData(), 1000 * 60 * 60); ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Using standard `setInterval` for background tasks outside of the NestJS lifecycle prevents proper tracking and memory management. It can lead to memory leaks, duplicate task execution in clustered environments, and difficult testing. #### ✅ Best Practice ```typescript @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT) @@ -394,7 +394,7 @@ handleCron() { this.cleanupData(); } @Post() // Использование HTTP для межсервисного общения ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Using standard HTTP requests for internal microservice-to-microservice communication introduces significant network latency and point-to-point coupling. It prevents utilizing asynchronous, resilient message brokers like RabbitMQ or Kafka. #### ✅ Best Practice ```typescript @MessagePattern({ cmd: 'get_user' }) @@ -409,7 +409,7 @@ getUser(data: unknown) { return this.userService.findById(data.id); } @Get('ping') ping() { return 'pong'; } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Using a simple 'ping' endpoint that always returns 200 OK does not verify the actual health of the application's dependencies (e.g., database connection). Orchestrators may mistakenly keep a broken container in the load balancer pool. #### ✅ Best Practice ```typescript @Get('health') @@ -426,7 +426,7 @@ check() { return this.health.check([() => this.db.pingCheck('database')]); } @Injectable() class UserService { constructor(private auth: AuthService) {} } ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Circular dependencies (Module A imports Module B, which imports Module A) cause resolution failures during application bootstrap. They are a strong indicator of architectural design flaws and tightly coupled domain boundaries. #### ✅ Best Practice ```typescript @Injectable() class UserService { constructor(@Inject(forwardRef(() => AuthService)) private auth: AuthService) {} } @@ -440,7 +440,7 @@ Insecure or unoptimized implementation that can cause performance bottlenecks, m // Модуль B импортирует Модуль А, Модуль С импортирует Модуль А... ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Duplicating module imports across the application instead of utilizing a structured Shared or Core module leads to excessive boilerplate and potential circular dependency issues. It makes the dependency graph unnecessarily complex. #### ✅ Best Practice ```typescript @Module({ imports: [DatabaseModule], exports: [DatabaseModule] }) @@ -453,7 +453,7 @@ export class CoreModule {} // Глобальный фасад #### ❌ Bad Practice // Определение логгера запросов в каждом месте #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Defining repetitive middleware logic (like request logging) locally in multiple controllers violates the DRY principle. It leads to inconsistent implementation and makes it difficult to enforce global policies. #### ✅ Best Practice ```typescript export class AppModule implements NestModule { @@ -469,7 +469,7 @@ export class AppModule implements NestModule { const service = new UserService(new Database()); // Реальная БД в тестах ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Connecting to a real database in unit tests makes tests slow, flaky, and dependent on external state. It violates the core principle of isolated unit testing, which should rely on mocked dependencies. #### ✅ Best Practice ```typescript const module = await Test.createTestingModule({ @@ -485,7 +485,7 @@ const module = await Test.createTestingModule({ if (!isEmailUnique(dto.email)) throw error; // Ручная логика в сервисе ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Implementing validation logic inside business services rather than utilizing `class-validator` constraints tightly couples validation to execution. It bypasses the global validation pipe, leading to inconsistent error formatting. #### ✅ Best Practice ```typescript @ValidatorConstraint({ async: true }) @@ -500,7 +500,7 @@ export class IsUniqueConstraint implements ValidatorConstraintInterface { ... } #### ❌ Bad Practice // Обработка потоков руками #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Handling binary file streams manually without the built-in Multer interceptors is highly error-prone. It drastically increases the risk of memory exhaustion, incomplete uploads, and unhandled boundary parsing exceptions. #### ✅ Best Practice ```typescript @Post('upload') @@ -516,7 +516,7 @@ uploadFile(@UploadedFile() file: Express.Multer.File) {} const { password, ...safeUser } = user; // Ручное удаление пароля ``` #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Manually deleting sensitive fields (like passwords) from response objects before returning them is error-prone. Forgetting to do this in even one place exposes sensitive data to the client, creating a critical security vulnerability. #### ✅ Best Practice ```typescript class UserEntity { @Exclude() password: string; } @@ -531,7 +531,7 @@ class UserEntity { @Exclude() password: string; } #### ❌ Bad Practice // Вызов специфичных методов req.expressMethod #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Directly accessing platform-specific request/response objects (like Express's `req.ip`) tightly couples the application to the underlying HTTP framework. This prevents easy migration to higher-performance engines like Fastify. #### ✅ Best Practice ```typescript const app = await NestFactory.create(AppModule, new FastifyAdapter()); @@ -543,7 +543,7 @@ const app = await NestFactory.create(AppModule, new Fast #### ❌ Bad Practice // Приложение убивается мгновенно, прерывая активные соединения #### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Immediate process termination severs active connections and leaves database operations in an unknown state. This causes data corruption and forces clients to experience unhandled connection drops. #### ✅ Best Practice ```typescript app.enableShutdownHooks(); diff --git a/backend/nodejs/readme.md b/backend/nodejs/readme.md index 24e9840..fe8650f 100644 --- a/backend/nodejs/readme.md +++ b/backend/nodejs/readme.md @@ -59,7 +59,7 @@ app.post('/hash', (req, res) => { }); ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Synchronous operations on the main thread block the Event Loop, halting all incoming API requests. This leads to severe performance degradation, unpredictable latency, and potential denial-of-service (DoS) vulnerabilities in high-traffic environments. ### ✅ Best Practice ```javascript const crypto = require('crypto'); @@ -79,7 +79,7 @@ Never use synchronous methods (`*Sync`) on the main thread for crypto, I/O, or h /server.js (Contains routes, DB connections, and logic all in one 1500-line file) ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +A monolithic file structure tightly couples routing, business logic, and data access. This lack of architectural boundaries makes the codebase difficult to test, increases merge conflicts in team environments, and hinders the ability of AI Agents to predictably traverse the logic tree. ### ✅ Best Practice ```text /src @@ -99,7 +99,7 @@ const port = process.env.PORT || 3000; // Continuing application startup without validating required variables. ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Failing to validate environment variables at startup allows the application to boot into an invalid state. This can lead to cryptic runtime crashes, unintended connections to production databases during development, or silent failures in authentication mechanisms. ### ✅ Best Practice ```javascript const requiredEnv = ['DATABASE_URL', 'JWT_SECRET', 'PORT']; @@ -119,7 +119,7 @@ Fail fast. Validate all necessary environment variables upon application startup if (!user) throw new Error('User not found'); ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Throwing generic Error objects strips contextual metadata (like HTTP status codes or operational vs. programming flags). This prevents global error handlers from predictably formatting responses, potentially leaking stack traces to clients. ### ✅ Best Practice ```javascript class AppError extends Error { @@ -138,7 +138,7 @@ Extend the built-in `Error` object to create custom operational errors. This all ### ❌ Bad Practice // Ignoring process-level events, allowing the app to run in an unpredictable state after an error. ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Ignoring process-level exceptions leaves the application running in an unpredictable, potentially corrupted memory state. This can cause subsequent requests to fail silently or behave erratically, requiring a full process restart to recover safety. ### ✅ Best Practice ```javascript process.on('uncaughtException', (err) => { @@ -158,7 +158,7 @@ Always capture `uncaughtException` and `unhandledRejection`. Log the fatal error ### ❌ Bad Practice // Sending default headers that expose the framework, like `X-Powered-By: Express`. ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Exposing default framework headers (e.g., `X-Powered-By: Express`) provides attackers with valuable fingerprinting information. This allows automated scanners to quickly identify the technology stack and exploit known framework-specific vulnerabilities. ### ✅ Best Practice ```javascript // Example using Express + Helmet, but applies generically to HTTP responses @@ -172,7 +172,7 @@ Sanitize outgoing HTTP headers to prevent information leakage about the server i ### ❌ Bad Practice // Application crashes abruptly during deployments, interrupting active user requests and corrupting database transactions. ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Terminating the process abruptly interrupts active user requests and orphans in-flight database transactions. This can lead to data corruption, inconsistent state, and degraded user experience during deployments or container scaling. ### ✅ Best Practice ```javascript process.on('SIGTERM', () => { @@ -196,7 +196,7 @@ Listen for termination signals (`SIGTERM`, `SIGINT`). Finish processing ongoing const user = await db.query(`SELECT * FROM users WHERE email = '${req.body.email}'`); ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Blindly trusting client input enables severe vulnerabilities like SQL/NoSQL Injection and Cross-Site Scripting (XSS). Without strict schema validation at the transport boundary, malicious payloads can compromise data integrity and system security. ### ✅ Best Practice ```javascript // Utilizing parameterized queries and a validation library like Joi or Zod @@ -218,7 +218,7 @@ function processImage(buffer) { } ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Executing CPU-intensive tasks directly on the main thread starves the Event Loop of resources. This causes the application to become unresponsive to other concurrent API requests, drastically reducing throughput and scalability. ### ✅ Best Practice ```javascript const { Worker } = require('worker_threads'); @@ -240,7 +240,7 @@ Offload CPU-intensive operations (image processing, video encoding, heavy crypto console.log('User logged in', userId); ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Relying on standard `console.log` produces unstructured output that is impossible for monitoring systems to query or alert on efficiently. This severely degrades observability, making it difficult to trace errors across distributed systems or correlate user actions. ### ✅ Best Practice ```javascript const winston = require('winston'); diff --git a/backend/readme.md b/backend/readme.md index 50919f4..8c7e7e3 100644 --- a/backend/readme.md +++ b/backend/readme.md @@ -55,7 +55,7 @@ app.get('/users/:id', async (req, res) => { }); ``` ### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. +Returning database ORM models directly in HTTP responses tightly couples the database schema to the API contract. This exposes sensitive internal fields (like password hashes or internal IDs) and prevents evolving the database schema without breaking API clients. ### ✅ Best Practice ```javascript // Mapping the database entity to a specialized DTO