agentleFS
girijashankarjgirijashankarj/cursor-handbook/.cursor/rules/backend/handler-patterns.mdc

cursor-handbook / backend

Cursor rule31 starsChanged 3 months agoMITView on GitHub

Backend handler/controller pattern rules and flow. Apply when editing handlers or API routes.

The file

We split this handler-patterns.mdc into the rules it gives an agent

11 rules. About 0 are common, 10 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈10

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Every API handler MUST follow this {{CONFIG.patterns.handlerFlowSteps}}-step flow:

    line 10
  2. Distinctive:

    Use dependency injection for external services

    line 85
  3. Distinctive:

    Always pass correlationId through the entire flow

    line 87
  4. Distinctive:

    Don't put business logic in validate-request — validation only

    line 90
  5. Distinctive:

    Don't skip validate-business — always check entity state before operation

    line 91
  6. Distinctive:

    Don't call DB/services from pre-processing — only transform data

    line 92
  7. Distinctive:

    Don't await post-operation in handler — fire-and-forget or queue

    line 93
  8. Distinctive:

    Don't return raw result — always use formatResponse envelope

    line 94
  9. Distinctive:

    Idempotency for POST: Use idempotency key header.

    line 106
  10. Distinctive:

    Concurrent updates: Use optimistic locking (version field) or last-write-wins with audit

    line 108
  11. Very specific:

    Use @create-handler skill when creating new handlers

    line 111

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 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
handler-patterns.mdc
---
description: "Backend handler/controller pattern rules and flow. Apply when editing handlers or API routes."
alwaysApply: false
globs: "**/handlers/**/*.ts,**/api/**/*.ts,**/*.handler.ts,**/*.controller.ts"
---

# Handler Pattern Rules

## Handler Flow
Every API handler MUST follow this {{CONFIG.patterns.handlerFlowSteps}}-step flow:

### Step-by-Step Flow
1. **Validate Request** — Schema validation, type checking, required fields
2. **Validate Business** — Business rule validation, entity state checks
3. **Pre-Processing** — Data transformation, enrichment, defaults
4. **Operation** — Core business logic execution
5. **Post-Operation** — Side effects (events, notifications, cache invalidation)
6. **Response** — Format and return response
7. **Exit** — Cleanup, logging

### Handler Directory Structure
```
{{CONFIG.paths.handlerBasePath}}/{entity}/{operation}/
├── {{CONFIG.fileNames.handlerEntry}}        # Handler entry point
├── {{CONFIG.folderNames.logic}}/
│   ├── validate-request.ts                   # Step 1
│   ├── validate-business.ts                  # Step 2
│   ├── pre-processing.ts                     # Step 3
│   ├── operation.ts                          # Step 4
│   ├── post-operation.ts                     # Step 5
│   └── response.ts                           # Step 6
└── {{CONFIG.folderNames.schemas}}/
    ├── {{CONFIG.fileNames.requestSchema}}    # Request validation schema
    └── {{CONFIG.fileNames.responseSchema}}   # Response format schema
```

### Handler Entry Point Template
```{{CONFIG.techStack.language}}
import { Request, Response, NextFunction } from '{{CONFIG.techStack.framework}}';
import { validateRequest } from './logic/validate-request';
import { validateBusiness } from './logic/validate-business';
import { preProcessing } from './logic/pre-processing';
import { operation } from './logic/operation';
import { postOperation } from './logic/post-operation';
import { formatResponse } from './logic/response';
import { logger } from '{{CONFIG.paths.commonPath}}/logger';

export async function handler(req: Request, res: Response, next: NextFunction) {
  const correlationId = req.headers['x-correlation-id'] as string;
  const log = logger.child({ correlationId, operation: 'handler-name' });

  try {
    // Step 1: Validate Request
    const validatedInput = await validateRequest(req.body);

    // Step 2: Validate Business Rules
    await validateBusiness(validatedInput);

    // Step 3: Pre-Processing
    const processedData = await preProcessing(validatedInput);

    // Step 4: Core Operation
    const result = await operation(processedData);

    // Step 5: Post-Operation (async side effects)
    await postOperation(result);

    // Step 6: Response
    const response = formatResponse(result);

    // Step 7: Exit
    log.info({ status: 'success' }, 'Handler completed');
    return res.status(200).json(response);
  } catch (error) {
    log.error({ error: error.message }, 'Handler failed');
    next(error);
  }
}
```

## Rules
- Each logic step MUST be a pure function (no side effects except in post-operation)
- Each logic file should have a single default export
- Schemas MUST be JSON Schema format for request/response validation
- Use dependency injection for external services
- Handler functions MUST be async
- Always pass correlationId through the entire flow

## Anti-patterns
- Don't put business logic in validate-request — validation only
- Don't skip validate-business — always check entity state before operation
- Don't call DB/services from pre-processing — only transform data
- Don't await post-operation in handler — fire-and-forget or queue
- Don't return raw result — always use formatResponse envelope

## Examples
```ts
// BAD: correlationId not passed
const result = await operation(processedData);

// GOOD: correlationId in context
const result = await operation({ ...processedData, correlationId });
```

## Edge Cases
- **Idempotency for POST**: Use idempotency key header; check before create
- **Pagination for list**: Return cursor + hasNextPage; never unbounded
- **Concurrent updates**: Use optimistic locking (version field) or last-write-wins with audit

## Related
- Use `@create-handler` skill when creating new handlers
- See `@api-design` for URL structure and response envelope

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.