Глава 10. Работа с базами кодов
10.1. Индексация проекта
Cursor автоматически индексирует ваш проект для быстрого поиска и понимания кода.
Процесс индексации
При открытии проекта Cursor:
1. Сканирует все файлы (с учетом `.cursorignore`)
2. Создает синтаксическое дерево (AST)
3. Генерирует embeddings для семантического поиска
4. Строит граф зависимостей
5. Кэширует результаты
Индикаторы индексации
В статус-баре показывается прогресс:Indexing: 1234/5678 files (23%)
После завершения:✓ Indexed: 5678 files
Управление индексацией
Переиндексация:
Command Palette → "Cursor: Reindex Project"
Исключение файлов:
Создайте `.cursorignore` (синтаксис как `.gitignore`):
node_modules/
dist/
build/
*.log
.env
coverage/
*.min.js
public/assets/
Приоритизация:
Cursor автоматически приоритизирует часто используемые файлы.
Оптимизация для больших проектов
Для проектов >10,000 файлов:
1. **Исключите ненужные директории**:.cursorignore
*.test.js # Exclude tests from main index
docs/
examples/
legacy/
2. **Разделите на воркспейсы**:
Вместо одного огромного проекта, откройте конкретные модули:
/project
/frontend <- Открыть этот воркспейс
/backend <- Или этот
/shared
3. **Используйте .cursor/config.json**:
```json
{
"indexing": {
"maxFiles": 50000,
"excludePatterns": ["**/*.md", "**/test/**"],
"followSymlinks": false
}
}10.2. Семантический поиск
В отличие от текстового поиска (Cmd/Ctrl+F), семантический поиск находит код по смыслу, а не по точному совпадению.
Как использовать
В Chat:
You: Где в коде происходит аутентификация пользователя?
AI: [Показывает релевантные файлы]
Аутентификация обрабатывается в нескольких местах:
1. middleware/auth.js - проверка JWT токена
2. controllers/authController.js - логин/регистрация
3. utils/passport.js - стратегии passport.js
Хотите посмотреть какой-то конкретный файл?
В Composer:
При описании задачи Cursor автоматически находит релевантные файлы:
You: Добавь валидацию email при регистрации
Composer: [Автоматически включает в контекст]
- controllers/authController.js
- validators/userValidator.js
- models/User.js
Symbol Search:
Command Palette → "Go to Symbol in Workspace" (Cmd/Ctrl+T)
Найдет функции, классы, переменные по имени или описанию:
Поиск: "calculate discount"
Результаты:
- calculateDiscount() в utils/pricing.js
- getDiscountedPrice() в models/Product.js
- applyDiscount() в services/OrderService.jsПримеры семантического поиска
Поиск по функциональности:
"Где отправляются email уведомления?"
→ Находит: emailService.js, notificationService.js, mailer.jsПоиск по паттерну:
"Покажи все функции, которые делают HTTP запросы"
→ Находит: все места с fetch, axios, http.get, и т.д.Поиск похожего кода:
You: [Выделите функцию]
Найди похожие функции в проекте
AI: Найдено 3 похожие функции:
1. getUserOrders() - похожая структура запроса
2. getProductReviews() - аналогичная обработка ошибок
3. fetchDashboardData() - схожая пагинация10.3. Навигация по большим кодовым базам
Breadcrumb Navigation
В верхней части редактора отображается путь:
src > components > Dashboard > UserProfile.tsx > UserProfile > renderКлик на любой элемент показывает структуру:
src
├─ components
│ ├─ Dashboard
│ │ ├─ UserProfile.tsx <- Вы здесь
│ │ ├─ Statistics.tsx
│ │ └─ ActivityFeed.tsxQuick Navigation с AI
You: Как пользователи добавляют товары в корзину?
AI: Процесс добавления в корзину:
1. User clicks "Add to Cart" button
components/ProductCard.tsx:45
2. Dispatches action to Redux
store/actions/cartActions.ts:12
3. Reducer updates cart state
store/reducers/cartReducer.ts:28
4. API call to backend
api/cart.ts:56
5. Database update
backend/services/CartService.ts:89
[Клик на любой файл открывает его в нужной строке]Call Hierarchy
Right-click на функции → "Show Call Hierarchy"
Показывает:
- Кто вызывает эту функцию (callers)
- Что эта функция вызывает (callees)
calculateTotal()
Called by:
├─ processOrder() [OrderService.ts:45]
├─ updateCart() [CartController.ts:78]
└─ generateInvoice() [InvoiceService.ts:123]
Calls:
├─ calculateTax()
├─ applyDiscount()
└─ formatCurrency()File Outline
View → Outline (Cmd/Ctrl+Shift+O)
Показывает структуру файла:
UserProfile.tsx
├─ Imports
├─ Interfaces
│ ├─ UserProfileProps
│ └─ UserStats
├─ UserProfile (Component)
│ ├─ useState hooks
│ ├─ useEffect hooks
│ ├─ handleEdit()
│ ├─ handleSave()
│ └─ render()
└─ Exports10.4. Понимание архитектуры проекта
AI может анализировать и объяснять архитектуру проекта.
Общий обзор
You: Объясни архитектуру этого проекта
AI: Анализ архитектуры:
## Паттерн
Приложение использует MVC (Model-View-Controller) архитектуру
с разделением на слои.
## Структура
### Frontend (React SPA)
- src/components/ - React компоненты (View)
- src/store/ - Redux для state management
- src/services/ - API клиенты
- src/hooks/ - Custom React hooks
- src/utils/ - Утилиты и хелперы
### Backend (Node.js + Express)
- server/routes/ - HTTP маршруты (Controller)
- server/controllers/ - Обработчики запросов
- server/services/ - Бизнес-логика
- server/models/ - Data models (Model)
- server/middleware/ - Промежуточные обработчики
- server/config/ - Конфигурация
### Database
- PostgreSQL для реляционных данных
- Redis для кэширования
## Поток данных
Client Request
↓
Router
↓
Middleware (auth, validation)
↓
Controller
↓
Service (business logic)
↓
Model/Repository
↓
Database
↓
Response back to client
## Ключевые паттерны
- Dependency Injection в сервисах
- Repository Pattern для database
- Middleware для cross-cutting concerns
- Custom hooks для reusable logic
## Масштабируемость
- Модульная структура
- Слабая связанность (loose coupling)
- API-first подход
- Готовность к микросервисамАнализ зависимостей
You: Покажи зависимости между модулями
AI: Граф зависимостей:
auth module
├─ depends on: database, jwt-utils, bcrypt
└─ used by: user-profile, admin-panel
user module
├─ depends on: database, auth, validation
└─ used by: dashboard, settings
product module
├─ depends on: database, image-upload
└─ used by: cart, wishlist, search
cart module
├─ depends on: product, user, payment
└─ used by: checkout
Circular dependencies: None ✓
Isolated modules: logging, email-service ✓Рекомендации по улучшению
You: Какие проблемы в архитектуре и как улучшить?
AI: Анализ и рекомендации:
## Проблемы
1. God Object: UserService (342 строки)
- Делает слишком много
- Трудно тестировать
- Рекомендация: разбить на UserAuthService, UserProfileService, UserPreferencesService
2. Tight Coupling
- CartController напрямую обращается к database
- Рекомендация: использовать CartRepository
3. Отсутствие интерфейсов
- Сервисы не имеют определенных контрактов
- Рекомендация: создать TypeScript интерфейсы
4. Mixed Concerns
- API routes содержат бизнес-логику
- Рекомендация: вынести в service layer
## План рефакторинга
Phase 1: Разделение ответственностей
- Создать repository layer
- Вынести бизнес-логику из controllers
Phase 2: Интерфейсы и типы
- Определить contracts
- Добавить TypeScript типы
Phase 3: Тестирование
- Unit tests для services
- Integration tests для API10.5. Документирование кода
AI может генерировать и поддерживать документацию.
Inline Documentation
You: [Выделите функцию]
Добавь подробную JSDoc документацию
AI:/**
* Calculates the final price after applying discounts and taxes
*
* @param {number} basePrice - The original price before any modifications
* @param {Object} options - Calculation options
* @param {number} [options.discountPercent=0] - Discount percentage (0-100)
* @param {number} [options.taxRate=0] - Tax rate as decimal (e.g., 0.08 for 8%)
* @param {boolean} [options.roundToNearest=true] - Round result to nearest cent
*
* @returns {number} The final calculated price
*
* @throws {Error} If basePrice is negative
* @throws {Error} If discountPercent is not between 0-100
*
* @example
* // Basic usage
* const price = calculateFinalPrice(100);
* // => 100
*
* @example
* // With discount and tax
* const price = calculateFinalPrice(100, {
* discountPercent: 10,
* taxRate: 0.08
* });
* // => 97.20 (100 - 10% = 90, 90 * 1.08 = 97.20)
*/
function calculateFinalPrice(
basePrice: number,
options: {
discountPercent?: number;
taxRate?: number;
roundToNearest?: boolean;
} = {}
): number {
// Implementation
}
README Generation
You: Создай README.md для этого проекта
AI: [Генерирует]# Project Name
Brief description of what this project does.
## Features
- Fast and efficient
- Secure authentication
- Responsive design
- Real-time updates
## Tech Stack
**Frontend:**
- React 18
- TypeScript
- Tailwind CSS
- Redux Toolkit
**Backend:**
- Node.js
- Express
- PostgreSQL
- Redis
## Getting Started
### Prerequisites
- Node.js 18+
- PostgreSQL 14+
- Redis 6+
### Installation
```bash
# Clone repository
git clone https://github.com/username/project.git
# Install dependencies
cd project
npm install
# Setup environment variables
cp .env.example .env
# Edit .env with your configuration
# Run migrations
npm run migrate
# Start development server
npm run dev
Environment Variables
| Variable | Description | Default |
|---|---|---|
PORT
|
Server port |
3000
|
DATABASE_URL
|
PostgreSQL connection string | - |
REDIS_URL
|
Redis connection string | - |
JWT_SECRET
|
Secret for JWT tokens | - |
Project Structure
project/
├── src/
│ ├── components/ # React components
│ ├── store/ # Redux store
│ ├── services/ # API services
│ └── utils/ # Utilities
├── server/
│ ├── routes/ # API routes
│ ├── controllers/ # Request handlers
│ ├── services/ # Business logic
│ └── models/ # Data models
└── tests/ # Test files
API Documentation
Authentication
POST /api/auth/register
Register a new user
Request:
{
"email": "user@example.com",
"password": "securePassword123",
"name": "John Doe"
}
Response:
{
"success": true,
"data": {
"user": { ... },
"token": "jwt-token-here"
}
}
Testing
# Run all tests
npm test
# Run with coverage
npm run test:coverage
# Run specific test file
npm test UserService.test.ts
Deployment
Docker
# Build image
docker build -t project-name .
# Run container
docker run -p 3000:3000 --env-file .env project-name
Production
See DEPLOYMENT.md for detailed deployment instructions.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
License
This project is licensed under the MIT License - see LICENSE file.
Contact
Your Name - @twitter
Project Link: https://github.com/username/project
**API Documentation**You: Создай OpenAPI/Swagger документацию для @routes/users.ts
AI:
```yaml
openapi: 3.0.0
info:
title: User Management API
version: 1.0.0
description: API for managing users
paths:
/api/users:
get:
summary: Get all users
tags:
- Users
parameters:
- in: query
name: page
schema:
type: integer
default: 1
- in: query
name: limit
schema:
type: integer
default: 10
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
success:
type: boolean
data:
type: array
items:
$ref: '#/components/schemas/User'
meta:
type: object
properties:
total:
type: integer
page:
type: integer
pages:
type: integer
post:
summary: Create a new user
tags:
- Users
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserRequest'
responses:
'201':
description: User created
'400':
description: Validation error
components:
schemas:
User:
type: object
properties:
id:
type: string
format: uuid
email:
type: string
format: email
name:
type: string
createdAt:
type: string
format: date-time
CreateUserRequest:
type: object
required:
- email
- password
- name
properties:
email:
type: string
format: email
password:
type: string
minLength: 8
name:
type: string
minLength: 2
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
security:
- BearerAuth: []