Перейти к содержанию
Skillpedia
API и серверы (бэкенд)33k · #8726

backend-dev-guidelines

Что он делает

Этот скилл даёт вашему ИИ правила для бэкендов на Node.js, Express и TypeScript. Он нужен разработчикам, которым важно, чтобы маршруты, сервисы и доступ к данным были организованы.

Когда использовать

  • ✓Когда вы добавляете новые маршруты, контроллеры или сервисы в API на Express.
  • ✓Когда вы настраиваете новый микросервис с отслеживанием ошибок и конфигурацией.
  • ✓Когда вы добавляете доступ к базе через Prisma или проверку входных данных через Zod.

Ссылка на скилл

https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/development/backend-dev-guidelines/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/development/backend-dev-guidelines/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Добавь новый эндпоинт для создания счетов в моём API на Express, по нашей многоуровневой структуре.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Скилл показывает агенту многоуровневый подход: маршруты только направляют запросы, контроллеры обрабатывают их, сервисы содержат бизнес-логику, а репозитории работают с данными. Агент следует этому, когда пишет или меняет код.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

Backend Development Guidelines

Purpose

Establish consistency and best practices across backend microservices (blog-api, auth-service, notifications-service) using modern Node.js/Express/TypeScript patterns.

When to Use This Skill

Automatically activates when working on:

  • Creating or modifying routes, endpoints, APIs
  • Building controllers, services, repositories
  • Implementing middleware (auth, validation, error handling)
  • Database operations with Prisma
  • Error tracking with Sentry
  • Input validation with Zod
  • Configuration management
  • Backend testing and refactoring

Quick Start

New Backend Feature Checklist

  • Route: Clean definition, delegate to controller
  • 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

  • Directory structure (see architecture-overview.md)
  • instrument.ts for Sentry
  • unifiedConfig setup
  • BaseController class
  • Middleware stack
  • Error boundary
  • Testing framework

Architecture Overview

Layered Architecture

HTTP Request
    ↓
Routes (routing only)
    ↓
Controllers (request handling)
    ↓
Services (business logic)
    ↓
Repositories (data access)
    ↓
Database (Prisma)

Key Principle: Each layer has ONE responsibility.

See architecture-overview.md for complete details.


Directory Structure

service/src/
├── 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:

  • Controllers: PascalCase - UserController.ts
  • Services: camelCase - userService.ts
  • Routes: camelCase + Routes - userRoutes.ts
  • Repositories: PascalCase + Repository - UserRepository.ts

Core Principles (7 Key Rules)

1. Routes Only Route, Controllers Control

// ❌ NEVER: Business logic in routes
router.post('/submit', async (req, res) => {
    // 200 lines of logic
});

// ✅ ALWAYS: Delegate to controller
router.post('/submit', (req, res) => controller.submit(req, res));

2. All Controllers Extend BaseController

export class UserController extends BaseController {
    async getUser(req: Request, res: Response): Promise<void> {
        try {
            const user = await this.userService.findById(req.params.id);
            this.handleSuccess(res, user);
        } catch (error) {
            this.handleError(error, res, 'getUser');
        }
    }
}

3. All Errors to Sentry

try {
    await operation();
} catch (error) {
    Sentry.captureException(error);
    throw error;
}

4. Use unifiedConfig, NEVER process.env

// ❌ NEVER
const timeout = process.env.TIMEOUT_MS;

// ✅ ALWAYS
import { config } from './config/unifiedConfig';
const timeout = config.timeouts.default;

5. Validate All Input with Zod

const schema = z.object({ email: z.string().email() });
const validated = schema.parse(req.body);

6. Use Repository Pattern for Data Access

// Service → Repository → Database
const users = await userRepository.findActive();

7. Comprehensive Testing Required

describe('UserService', () => {
    it('should create user', async () => {
        expect(user).toBeDefined();
    });
});

Common Imports

// 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 {
Частые вопросы

Что такое многоуровневая структура?

Она разделяет маршруты, контроллеры, сервисы и репозитории, поэтому у каждого уровня одна задача.

Какие инструменты он охватывает?

Он охватывает Prisma, Zod, Sentry, единую конфигурацию и внедрение зависимостей.

Есть ли тестирование?

Да. Чек-лист включает модульные и интеграционные тесты.

Подробности

Оригинальное описание автора

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.

repo: davila7/claude-code-templates

Популярность

Звёзды на GitHub
33k
Место в рейтинге
#8726
Лицензия
MIT
Обновлён
02.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы