agentleFS
AlessandroMartiniAlessandroMartini/Awesome_IA_Rules/.cursor/rules/backend/node-bff-backend.mdc

Awesome_IA_Rules / backend

Cursor rule1 starsChanged 3 days agoMITView on GitHub

Node.js and TypeScript Backend / BFF architecture, Zod validation, App/Gw DTOs, error handling, and testing

The file

We split this node-bff-backend.mdc into the rules it gives an agent

6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Zero Business Logic: Never perform domain calculations, data aggregation, or direct gateway calls inside a controller.

    line 55
  2. Very specific:

    Always await promises or handle rejections explicitly.

    line 92
  3. Very specific:

    Use Promise.allSettled when aggregating independent downstream calls where partial degradation is acceptable, or Promise.all when all calls …

    line 93
  4. Very specific:

    Always preserve the error chain using standard ES2022 Error cause (throw new FailedDependencyError('Upstream payment gateway failed', { …

    line 108
  5. Distinctive:

    Never expose upstream stack traces, raw Axios/Fetch error objects, or internal URLs in the HTTP JSON response.

    line 109
  6. Very specific:

    AAA + Builder Pattern: Every test must follow Arrange, Act, Assert (single Act per test) and construct test fixtures via fluent Builders …

    line 115

≈ “Common” is an estimate: at least 1 in 5 of the 6,668 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
node-bff-backend.mdc
---
description: "Node.js and TypeScript Backend / BFF architecture, Zod validation, App/Gw DTOs, error handling, and testing"
globs: "{api,server,backend,src}/**/*.ts"
alwaysApply: false
---

# Node.js / TypeScript Backend & BFF Engineering Standards

> **Scope**: All Node.js / TypeScript backend and Backend-for-Frontend (BFF) source and test files (`{api,server,backend,src}/**/*.ts`).
> **Mandate**: Build modular, type-safe, resilient Node.js/TypeScript services and BFFs using Clean & Hexagonal Architecture, runtime Zod schema validation, strict layer DTO isolation, and deterministic testing.

---

## 1. Modular Layered Architecture

Organize code into self-contained feature modules under `api/modules/` (or `src/modules/`) with strict inward boundaries: **`Routes → Controllers → Applications → Gateways`**.

```text
api/
├── index.ts                              # Server bootstrap & global middlewares
├── modules/
│   └── {feature}/
│       ├── routes/                       # Route definitions & middleware wiring
│       │   └── {feature}.routes.ts
│       ├── controllers/                  # HTTP transport layer
│       │   ├── schemas/                  # Zod validation schemas (Params, Query, Body)
│       │   ├── {feature}.controller.ts
│       │   └── {feature}.controller.spec.ts
│       ├── applications/                 # Use case orchestration & business rules
│       │   ├── dto/                      # Application DTOs (App{Name}Dto)
│       │   ├── {feature}.application.ts
│       │   └── {feature}.application.spec.ts
│       └── gateways/                     # Outbound external service / DB adapters
│           └── {service}/
│               ├── dto/                  # Gateway DTOs (Gw{Name}Dto)
│               ├── {service}.config.ts   # Endpoint timeout, retry & circuit breaker config
│               ├── {service}.gateway.ts
│               └── {service}.gateway.spec.ts
├── shared/
│   ├── errors/                           # Semantic error classes & global error handler
│   ├── http/                             # Base resilient HTTP client executor
│   └── middlewares/                      # Auth, request context, Zod validation middlewares
```

---

## 2. Layer Responsibilities & DTO Isolation

### 1. Routes Layer (`routes/`)
- Wire HTTP verbs, authentication/authorization middlewares, Zod validation middlewares, and controller handlers.
- Perform explicit dependency injection (wiring Gateway → Application → Controller).

### 2. Controllers Layer (`controllers/`)
- **Transport Only**: Extract validated parameters/body, extract caller identity strictly from the verified `req.auth` context (never trust `req.query.userId` or `req.body.userId`), build the request context (`traceId`, `actorId`, `locale`), invoke the Application layer, and return the HTTP response.
- **Zero Business Logic**: Never perform domain calculations, data aggregation, or direct gateway calls inside a controller.
- **Validation via Zod Schemas (`controllers/schemas/`)**:
  - Naming: `{Action}{Entity}{Source}Schema` (e.g., `GetOrderParamsSchema`, `CreateOrderBodySchema`).
  - Export inferred TypeScript types (`export type CreateOrderBody = z.infer<typeof CreateOrderBodySchema>`).

```typescript
import { z } from 'zod';

export const CreatePaymentBodySchema = z.object({
  customerId: z.string().uuid('customerId must be a valid UUID'),
  amount: z.number().positive('amount must be greater than zero'),
  currency: z.string().length(3, 'currency must be a 3-letter ISO code'),
});

export type CreatePaymentBody = z.infer<typeof CreatePaymentBodySchema>;
```

### 3. Applications Layer (`applications/`)
- **Business Orchestration**: Coordinate one or more gateways, enforce domain/business rules, and transform Gateway DTOs into Application Output DTOs.
- **No HTTP Knowledge**: Applications must never import `Request`, `Response`, `NextFunction`, or HTTP status codes.
- **DTO Naming (`applications/dto/`)**: Prefix with `App` (`AppCreatePaymentInputDto`, `AppPaymentOutputDto`).

### 4. Gateways Layer (`gateways/`)
- **External Integration**: Encapsulate all outbound HTTP, gRPC, cache, or database calls using a shared resilient client executor (enforcing timeouts, bounded retries, circuit breakers, and `snake_case ↔ camelCase` serialization).
- **DTO Naming (`gateways/{service}/dto/`)**: Prefix with `Gw` (`GwPaymentServiceResponseDto`). Never leak `Gw*Dto` types directly to Controllers or UI clients.

---

## 3. TypeScript & Node.js Quality Standards

- **Strict TypeScript**: Enable `"strict": true` in `tsconfig.json`. Never use `any`—use `unknown` with runtime type guards or Zod parsing when handling untrusted payloads.
- **Naming Conventions**:
  - Files: `kebab-case` with layer suffixes (`payment.controller.ts`, `payment.application.ts`, `payment.gateway.ts`, `payment.controller.spec.ts`).
  - Classes & Interfaces: `PascalCase` (`PaymentController`, `AppPaymentOutputDto`).
  - Functions & Variables: `camelCase` (`createPayment`, `isAuthorized`).
  - Constants: `SCREAMING_SNAKE_CASE` (`DEFAULT_TIMEOUT_MS`).
- **Async / Concurrency Safety**:
  - Always `await` promises or handle rejections explicitly; enable ESLint `@typescript-eslint/no-floating-promises`.
  - Use `Promise.allSettled` when aggregating independent downstream calls where partial degradation is acceptable, or `Promise.all` when all calls are strictly required.
  - Propagate `AbortSignal` / request timeouts to all outbound client calls.

---

## 4. Error Handling & Proximity Logging

### Layer Error Responsibilities
| Layer | Responsibility | Logging Rule |
| :--- | :--- | :--- |
| **Gateways** | Catch network/upstream failures, log technical details once at the source, and throw semantic infrastructure errors (`FailedDependencyError`, `ServiceUnavailableError`) chaining `{ cause: error }`. | `logger.error` once with `traceId`, `service`, `status` |
| **Applications** | Enforce business rules and throw semantic domain/business errors (`BadRequestError`, `ValidationError`, `ResourceNotFoundError`, `ConflictError`, `UnprocessableEntityError`). | **Never log** gateway errors (propagate cleanly) |
| **Controllers / Error Handler** | Catch errors and delegate to centralized `handleError(error, req, res)` middleware. | `4xx` → `logger.warn` / `404` → `logger.info` / Unlogged `500` → `logger.error` (never re-log errors already logged at a Gateway) |

### Security in Error Handling
- Always preserve the error chain using standard ES2022 `Error` cause (`throw new FailedDependencyError('Upstream payment gateway failed', { cause: err })`).
- Never expose upstream stack traces, raw Axios/Fetch error objects, or internal URLs in the HTTP JSON response. Return a sanitized RFC 9457 Problem Details or standard error envelope.

---

## 5. Unit & Integration Testing (`*.spec.ts`)

- **AAA + Builder Pattern**: Every test must follow **Arrange, Act, Assert** (single Act per test) and construct test fixtures via fluent **Builders** (`new PaymentDtoBuilder().withApprovedStatus().build()`) extending a shared `BaseBuilder<T>`. Never scatter raw object literals across tests.
- **Layer Isolation**:
  - *Controller Tests*: Mock `Application` methods; verify parameter extraction, auth context wiring, response status/JSON, and delegation to `handleError`.
  - *Application Tests*: Mock `Gateway` methods; test all business transformations, invariant validations, and error propagation.
  - *Gateway Tests*: Mock the underlying HTTP/DB client; verify outbound request parameters, `camelCase/snake_case` mapping, and upstream error translation (`424`/`503`).
- **Coverage Target**: `>= 95%` on Applications, Controllers, and Gateways.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.