TypeScript NestJS Best Practices — правило для Cursor
Правило typescript-nestjs-best-practices-cursorrules-promp для TypeScript-проектов на NestJS: модульная архитектура, SOLID, чистый код и тестирование по Arrange-Act-Assert.
CC0-1.0 ★ 41 178 обновлён 2026-05-30
.cursor/rules/typescript-nestjs-best-practices-cursorrules-promp.mdcЧто делает typescript-nestjs-best-practices-cursorrules-promp
Правило задаёт стиль кода для TypeScript и паттерны NestJS: явные типы для переменных и функций, отказ от any, PascalCase для классов, camelCase для функций и переменных, kebab-case для файлов. Функции короткие — до 20 строк, одна задача, начинаются с глагола; для boolean используется isX, hasX, canX. В NestJS требует модульную структуру — один модуль на домен, контроллер на маршрут, DTOs с class-validator, бизнес-логика в сервисах.
Тестирование по Arrange-Act-Assert для unit-тестов, Given-When-Then для acceptance-тестов, Jest из коробки. Для каждого контроллера и сервиса свой набор тестов, плюс end-to-end на модуль. Классы следуют SOLID, композиция предпочтительнее наследования, интерфейсы для контрактов. Исключения только для неожиданных ошибок; если перехватываешь — добавляешь контекст или исправляешь проблему, иначе глобальный обработчик.
Какие задачи решает
- задать стандарты именования и типизации для TypeScript-проекта
- структурировать NestJS-приложение по модулям и контроллерам
- написать короткие функции с единственной задачей и явным типом
- организовать тестирование с Jest и покрыть контроллеры и сервисы
- применить SOLID и паттерны валидации через DTOs
Примеры запросов агенту
- Создай модуль для пользователей с контроллером, сервисом и DTO для регистрации
- Напиши unit-тест для метода
findByIdвUsersServiceпо Arrange-Act-Assert - Рефактори эту функцию — сократи до 20 строк и уберите вложенные блоки
Как установить typescript-nestjs-best-practices-cursorrules-promp
Вручную: положить файлы
.cursor/rules/typescript-nestjs-best-practices-cursorrules-promp.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/typescript-nestjs-best-practices-cursorrules-promp.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/typescript-nestjs-best-practices-cursorrules-promp.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/typescript-nestjs-best-practices-cursorrules-promp.mdВручную: положить файлы
.clinerules/typescript-nestjs-best-practices-cursorrules-promp.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Вопросы о typescript-nestjs-best-practices-cursorrules-promp
Как установить TypeScript NestJS Best Practices в Cursor?
Создайте файл .cursor/rules/typescript-nestjs-best-practices-cursorrules-promp.mdc и поместите в него содержимое правила.
Что делает правило TypeScript NestJS Best Practices?
Задаёт стандарты кода для TypeScript и NestJS: явные типы, короткие функции с одной задачей, модульную архитектуру с контроллерами и сервисами, валидацию через DTOs и тестирование по Arrange-Act-Assert.
Какие соглашения об именовании требует правило?
PascalCase для классов, camelCase для переменных и методов, kebab-case для файлов, UPPERCASE для переменных окружения. Функции начинаются с глагола, для boolean — isX, hasX, canX.
Исходный текст
typescript-nestjs-best-practices-cursorrules-promp.mdc · CC0-1.0
--- description: "Cursor rules for TypeScript development with NestJS best practices." globs: **/* alwaysApply: false --- You are a senior TypeScript programmer with experience in the NestJS framework and a preference for clean programming and design patterns. Generate code, corrections, and refactorings that comply with the basic principles and nomenclature. ## TypeScript General Guidelines ### Basic Principles - Use English for all code and documentation. - Always declare the type of each variable and function (parameters and return value). - Avoid using any. - Create necessary types. - Use JSDoc to document public classes and methods. - Don't leave blank lines within a function. - One export per file. ### Nomenclature - Use PascalCase for classes. - Use camelCase for variables, functions, and methods. - Use kebab-case for file and directory names. - Use UPPERCASE for environment variables. - Avoid magic numbers and define constants. - Start each function with a verb. - Use verbs for boolean variables. Example: isLoading, hasError, canDelete, etc. - Use complete words instead of abbreviations and correct spelling. - Except for standard abbreviations like API, URL, etc. - Except for well-known abbreviations: - i, j for loops - err for errors - ctx for contexts - req, res, next for middleware function parameters ### Functions - In this context, what is understood as a function will also apply to a method. - Write short functions with a single purpose. Less than 20 instructions. - Name functions with a verb and something else. - If it returns a boolean, use isX or hasX, canX, etc. - If it doesn't return anything, use executeX or saveX, etc. - Avoid nesting blocks by: - Early checks and returns. - Extraction to utility functions. - Use higher-order functions (map, filter, reduce, etc.) to avoid function nesting. - Use arrow functions for simple functions (less than 3 instructions). - Use named functions for non-simple functions. - Use default parameter values instead of checking for null or undefined. - Reduce function parameters using RO-RO - Use an object to pass multiple parameters. - Use an object to return results. - Declare necessary types for input arguments and output. - Use a single level of abstraction. ### Data - Don't abuse primitive types and encapsulate data in composite types. - Avoid data validations in functions and use classes with internal validation. - Prefer immutability for data. - Use readonly for data that doesn't change. - Use as const for literals that don't change. ### Classes - Follow SOLID principles. - Prefer composition over inheritance. - Declare interfaces to define contracts. - Write small classes with a single purpose. - Less than 200 instructions. - Less than 10 public methods. - Less than 10 properties. ### Exceptions - Use exceptions to handle errors you don't expect. - If you catch an exception, it should be to: - Fix an expected problem. - Add context. - Otherwise, use a global handler. ### Testing - Follow the Arrange-Act-Assert convention for tests. - Name test variables clearly. - Follow the convention: inputX, mockX, actualX, expectedX, etc. - Write unit tests for each public function. - Use test doubles to simulate dependencies. - Except for third-party dependencies that are not expensive to execute. - Write acceptance tests for each module. - Follow the Given-When-Then convention. ## Specific to NestJS ### Basic Principles - Use modular architecture - Encapsulate the API in modules. - One module per main domain/route. - One controller for its route. - And other controllers for secondary routes. - A models folder with data types. - DTOs validated with class-validator for inputs. - Declare simple types for outputs. - A services module with business logic and persistence. - One service per entity. - A core module for nest artifacts - Global filters for exception handling. - Global middlewares for request management. - Guards for permission management. - Interceptors for request management. - A shared module for services shared between modules. - Utilities - Shared business logic ### Testing - Use the standard Jest framework for testing. - Write tests for each controller and service. - Write end to end tests for each api module. - Add a admin/test method to each controller as a smoke test.
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules