Update SKILL.md

This commit is contained in:
Munir Abbasi
2026-01-26 12:32:22 +05:00
committed by GitHub
parent 4d32a3e2af
commit c8de7f50f8

View File

@@ -1,125 +1,130 @@
--- ---
name: backend-dev-guidelines name: backend-dev-guidelines
description: Comprehensive backend development guide for Node.js/Express/TypeScript microservices. Use when creating routes, controllers, services, repositories, middleware, or working with Express APIs, Prisma database access, Sentry error tracking, Zod validation, unifiedConfig, dependency injection, or async patterns. Covers layered architecture (routes → controllers → services → repositories), BaseController pattern, error handling, performance monitoring, testing strategies, and migration from legacy patterns. description: Opinionated backend development standards for Node.js + Express + TypeScript microservices. Covers layered architecture, BaseController pattern, dependency injection, Prisma repositories, Zod validation, unifiedConfig, Sentry error tracking, async safety, and testing discipline.
--- ---
# Backend Development Guidelines # Backend Development Guidelines
## Purpose **(Node.js · Express · TypeScript · Microservices)**
Establish consistency and best practices across backend microservices (blog-api, auth-service, notifications-service) using modern Node.js/Express/TypeScript patterns. You are a **senior backend engineer** operating production-grade services under strict architectural and reliability constraints.
## When to Use This Skill Your goal is to build **predictable, observable, and maintainable backend systems** using:
Automatically activates when working on: * Layered architecture
- Creating or modifying routes, endpoints, APIs * Explicit error boundaries
- Building controllers, services, repositories * Strong typing and validation
- Implementing middleware (auth, validation, error handling) * Centralized configuration
- Database operations with Prisma * First-class observability
- Error tracking with Sentry
- Input validation with Zod This skill defines **how backend code must be written**, not merely suggestions.
- Configuration management
- Backend testing and refactoring
--- ---
## Quick Start ## 1. Backend Feasibility & Risk Index (BFRI)
### New Backend Feature Checklist Before implementing or modifying a backend feature, assess feasibility.
- [ ] **Route**: Clean definition, delegate to controller ### BFRI Dimensions (15)
- [ ] **Controller**: Extend BaseController
- [ ] **Service**: Business logic with DI
- [ ] **Repository**: Database access (if complex)
- [ ] **Validation**: Zod schema
- [ ] **Sentry**: Error tracking
- [ ] **Tests**: Unit + integration tests
- [ ] **Config**: Use unifiedConfig
### New Microservice Checklist | Dimension | Question |
| ----------------------------- | ---------------------------------------------------------------- |
| **Architectural Fit** | Does this follow routes → controllers → services → repositories? |
| **Business Logic Complexity** | How complex is the domain logic? |
| **Data Risk** | Does this affect critical data paths or transactions? |
| **Operational Risk** | Does this impact auth, billing, messaging, or infra? |
| **Testability** | Can this be reliably unit + integration tested? |
- [ ] Directory structure (see [architecture-overview.md](architecture-overview.md)) ### Score Formula
- [ ] instrument.ts for Sentry
- [ ] unifiedConfig setup ```
- [ ] BaseController class BFRI = (Architectural Fit + Testability) (Complexity + Data Risk + Operational Risk)
- [ ] Middleware stack ```
- [ ] Error boundary
- [ ] Testing framework **Range:** `-10 → +10`
### Interpretation
| BFRI | Meaning | Action |
| -------- | --------- | ---------------------- |
| **610** | Safe | Proceed |
| **35** | Moderate | Add tests + monitoring |
| **02** | Risky | Refactor or isolate |
| **< 0** | Dangerous | Redesign before coding |
--- ---
## Architecture Overview ## 2. When to Use This Skill
### Layered Architecture Automatically applies when working on:
``` * Routes, controllers, services, repositories
HTTP Request * Express middleware
* Prisma database access
Routes (routing only) * Zod validation
* Sentry error tracking
Controllers (request handling) * Configuration management
* Backend refactors or migrations
Services (business logic)
Repositories (data access)
Database (Prisma)
```
**Key Principle:** Each layer has ONE responsibility.
See [architecture-overview.md](architecture-overview.md) for complete details.
--- ---
## Directory Structure ## 3. Core Architecture Doctrine (Non-Negotiable)
### 1. Layered Architecture Is Mandatory
``` ```
service/src/ Routes → Controllers → Services → Repositories → Database
├── config/ # UnifiedConfig
├── controllers/ # Request handlers
├── services/ # Business logic
├── repositories/ # Data access
├── routes/ # Route definitions
├── middleware/ # Express middleware
├── types/ # TypeScript types
├── validators/ # Zod schemas
├── utils/ # Utilities
├── tests/ # Tests
├── instrument.ts # Sentry (FIRST IMPORT)
├── app.ts # Express setup
└── server.ts # HTTP server
``` ```
**Naming Conventions:** * No layer skipping
- Controllers: `PascalCase` - `UserController.ts` * No cross-layer leakage
- Services: `camelCase` - `userService.ts` * Each layer has **one responsibility**
- Routes: `camelCase + Routes` - `userRoutes.ts`
- Repositories: `PascalCase + Repository` - `UserRepository.ts`
--- ---
## Core Principles (7 Key Rules) ### 2. Routes Only Route
### 1. Routes Only Route, Controllers Control ```ts
// ❌ NEVER
```typescript router.post('/create', async (req, res) => {
// ❌ NEVER: Business logic in routes await prisma.user.create(...);
router.post('/submit', async (req, res) => {
// 200 lines of logic
}); });
// ✅ ALWAYS: Delegate to controller // ✅ ALWAYS
router.post('/submit', (req, res) => controller.submit(req, res)); router.post('/create', (req, res) =>
userController.create(req, res)
);
``` ```
### 2. All Controllers Extend BaseController Routes must contain **zero business logic**.
```typescript ---
### 3. Controllers Coordinate, Services Decide
* Controllers:
* Parse request
* Call services
* Handle response formatting
* Handle errors via BaseController
* Services:
* Contain business rules
* Are framework-agnostic
* Use DI
* Are unit-testable
---
### 4. All Controllers Extend `BaseController`
```ts
export class UserController extends BaseController { export class UserController extends BaseController {
async getUser(req: Request, res: Response): Promise<void> { async getUser(req: Request, res: Response): Promise<void> {
try { try {
const user = await this.userService.findById(req.params.id); const user = await this.userService.getById(req.params.id);
this.handleSuccess(res, user); this.handleSuccess(res, user);
} catch (error) { } catch (error) {
this.handleError(error, res, 'getUser'); this.handleError(error, res, 'getUser');
@@ -128,175 +133,210 @@ export class UserController extends BaseController {
} }
``` ```
### 3. All Errors to Sentry No raw `res.json` calls outside BaseController helpers.
```typescript ---
try {
await operation(); ### 5. All Errors Go to Sentry
} catch (error) {
```ts
catch (error) {
Sentry.captureException(error); Sentry.captureException(error);
throw error; throw error;
} }
``` ```
### 4. Use unifiedConfig, NEVER process.env `console.log`
❌ silent failures
❌ swallowed errors
```typescript ---
### 6. unifiedConfig Is the Only Config Source
```ts
// ❌ NEVER // ❌ NEVER
const timeout = process.env.TIMEOUT_MS; process.env.JWT_SECRET;
// ✅ ALWAYS // ✅ ALWAYS
import { config } from './config/unifiedConfig'; import { config } from '@/config/unifiedConfig';
const timeout = config.timeouts.default; config.auth.jwtSecret;
``` ```
### 5. Validate All Input with Zod ---
```typescript ### 7. Validate All External Input with Zod
const schema = z.object({ email: z.string().email() });
const validated = schema.parse(req.body); * Request bodies
* Query params
* Route params
* Webhook payloads
```ts
const schema = z.object({
email: z.string().email(),
});
const input = schema.parse(req.body);
``` ```
### 6. Use Repository Pattern for Data Access No validation = bug.
```typescript ---
// Service → Repository → Database
const users = await userRepository.findActive(); ## 4. Directory Structure (Canonical)
```
src/
├── config/ # unifiedConfig
├── controllers/ # BaseController + controllers
├── services/ # Business logic
├── repositories/ # Prisma access
├── routes/ # Express routes
├── middleware/ # Auth, validation, errors
├── validators/ # Zod schemas
├── types/ # Shared types
├── utils/ # Helpers
├── tests/ # Unit + integration tests
├── instrument.ts # Sentry (FIRST IMPORT)
├── app.ts # Express app
└── server.ts # HTTP server
``` ```
### 7. Comprehensive Testing Required ---
```typescript ## 5. Naming Conventions (Strict)
| Layer | Convention |
| ---------- | ------------------------- |
| Controller | `PascalCaseController.ts` |
| Service | `camelCaseService.ts` |
| Repository | `PascalCaseRepository.ts` |
| Routes | `camelCaseRoutes.ts` |
| Validators | `camelCase.schema.ts` |
---
## 6. Dependency Injection Rules
* Services receive dependencies via constructor
* No importing repositories directly inside controllers
* Enables mocking and testing
```ts
export class UserService {
constructor(
private readonly userRepository: UserRepository
) {}
}
```
---
## 7. Prisma & Repository Rules
* Prisma client **never used directly in controllers**
* Repositories:
* Encapsulate queries
* Handle transactions
* Expose intent-based methods
```ts
await userRepository.findActiveUsers();
```
---
## 8. Async & Error Handling
### asyncErrorWrapper Required
All async route handlers must be wrapped.
```ts
router.get(
'/users',
asyncErrorWrapper((req, res) =>
controller.list(req, res)
)
);
```
No unhandled promise rejections.
---
## 9. Observability & Monitoring
### Required
* Sentry error tracking
* Sentry performance tracing
* Structured logs (where applicable)
Every critical path must be observable.
---
## 10. Testing Discipline
### Required Tests
* **Unit tests** for services
* **Integration tests** for routes
* **Repository tests** for complex queries
```ts
describe('UserService', () => { describe('UserService', () => {
it('should create user', async () => { it('creates a user', async () => {
expect(user).toBeDefined(); expect(user).toBeDefined();
}); });
}); });
``` ```
--- No tests → no merge.
## Common Imports
```typescript
// Express
import express, { Request, Response, NextFunction, Router } from 'express';
// Validation
import { z } from 'zod';
// Database
import { PrismaClient } from '@prisma/client';
import type { Prisma } from '@prisma/client';
// Sentry
import * as Sentry from '@sentry/node';
// Config
import { config } from './config/unifiedConfig';
// Middleware
import { SSOMiddlewareClient } from './middleware/SSOMiddleware';
import { asyncErrorWrapper } from './middleware/errorBoundary';
```
--- ---
## Quick Reference ## 11. Anti-Patterns (Immediate Rejection)
### HTTP Status Codes
| Code | Use Case |
|------|----------|
| 200 | Success |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Server Error |
### Service Templates
**Blog API** (✅ Mature) - Use as template for REST APIs
**Auth Service** (✅ Mature) - Use as template for authentication patterns
---
## Anti-Patterns to Avoid
❌ Business logic in routes ❌ Business logic in routes
Direct process.env usage Skipping service layer
Missing error handling Direct Prisma in controllers
No input validation Missing validation
Direct Prisma everywhere process.env usage
❌ console.log instead of Sentry ❌ console.log instead of Sentry
❌ Untested business logic
--- ---
## Navigation Guide ## 12. Integration With Other Skills
| Need to... | Read this | * **frontend-dev-guidelines** → API contract alignment
|------------|-----------| * **error-tracking** → Sentry standards
| Understand architecture | [architecture-overview.md](architecture-overview.md) | * **database-verification** → Schema correctness
| Create routes/controllers | [routing-and-controllers.md](routing-and-controllers.md) | * **analytics-tracking** → Event pipelines
| Organize business logic | [services-and-repositories.md](services-and-repositories.md) | * **skill-developer** → Skill governance
| Validate input | [validation-patterns.md](validation-patterns.md) |
| Add error tracking | [sentry-and-monitoring.md](sentry-and-monitoring.md) |
| Create middleware | [middleware-guide.md](middleware-guide.md) |
| Database access | [database-patterns.md](database-patterns.md) |
| Manage config | [configuration.md](configuration.md) |
| Handle async/errors | [async-and-errors.md](async-and-errors.md) |
| Write tests | [testing-guide.md](testing-guide.md) |
| See examples | [complete-examples.md](complete-examples.md) |
--- ---
## Resource Files ## 13. Operator Validation Checklist
### [architecture-overview.md](architecture-overview.md) Before finalizing backend work:
Layered architecture, request lifecycle, separation of concerns
### [routing-and-controllers.md](routing-and-controllers.md) * [ ] BFRI ≥ 3
Route definitions, BaseController, error handling, examples * [ ] Layered architecture respected
* [ ] Input validated
### [services-and-repositories.md](services-and-repositories.md) * [ ] Errors captured in Sentry
Service patterns, DI, repository pattern, caching * [ ] unifiedConfig used
* [ ] Tests written
### [validation-patterns.md](validation-patterns.md) * [ ] No anti-patterns present
Zod schemas, validation, DTO pattern
### [sentry-and-monitoring.md](sentry-and-monitoring.md)
Sentry init, error capture, performance monitoring
### [middleware-guide.md](middleware-guide.md)
Auth, audit, error boundaries, AsyncLocalStorage
### [database-patterns.md](database-patterns.md)
PrismaService, repositories, transactions, optimization
### [configuration.md](configuration.md)
UnifiedConfig, environment configs, secrets
### [async-and-errors.md](async-and-errors.md)
Async patterns, custom errors, asyncErrorWrapper
### [testing-guide.md](testing-guide.md)
Unit/integration tests, mocking, coverage
### [complete-examples.md](complete-examples.md)
Full examples, refactoring guide
--- ---
## Related Skills ## 14. Skill Status
- **database-verification** - Verify column names and schema consistency
- **error-tracking** - Sentry integration patterns
- **skill-developer** - Meta-skill for creating and managing skills
**Status:** Stable · Enforceable · Production-grade
**Intended Use:** Long-lived Node.js microservices with real traffic and real risk
--- ---
**Skill Status**: COMPLETE ✅
**Line Count**: < 500 ✅
**Progressive Disclosure**: 11 resource files ✅