aws-dynamodb — правило для Cursor: что делает и как установить
Задаёт стандарты работы с AWS DynamoDB через AWS SDK v3 в Cursor. Помогает проектировать single-table схемы и выносить запросы в слой доступа к данным.
.cursor/rules/aws-dynamodb.mdcЧто делает aws-dynamodb
Инструкция настраивает Cursor на работу с базой AWS DynamoDB с помощью современного AWS SDK v3 и библиотеки @aws-sdk/lib-dynamodb. Моделирование строится вокруг принципа single-table design с составными ключами PK и SK, что избавляет от объединения таблиц на уровне приложения. Вторичные индексы (GSI) подключаются только тогда, когда основной ключ не закрывает нужный сценарий выборки.
Правило требует изолировать логику базы в репозитории или DAL вместо разрозненных вызовов в коде хэндлеров. Запросы к таблице типизируются через интерфейсы TypeScript и выполняются с помощью DynamoDBDocumentClient. Без выноса имени таблицы в переменные окружения вроде DYNAMODB_TABLE_NAME код не пройдёт проверку по этому стандарту. В шаблонах CloudFormation правило рекомендует режим биллинга PAY_PER_REQUEST либо автоскейлинг для снижения расходов.
Какие задачи решает
- спроектировать single-table архитектуру с составными ключами PK и SK
- вынести работу с DynamoDB в типизированный репозиторий
- настроить шаблон CloudFormation с шифрованием и режимом PAY_PER_REQUEST
- исключить хардкод имён таблиц и inline-вызовы SDK
Примеры запросов агенту
- Напиши репозиторий на TypeScript для сущностей User и Order через @aws-sdk/lib-dynamodb.
- Опиши схему таблицы в CloudFormation с режимом биллинга PAY_PER_REQUEST и шифрованием.
- Сделай выборку заказов пользователя по составному ключу PK и SK.
Как установить aws-dynamodb
Вручную: положить файлы
.cursor/rules/aws-dynamodb.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/aws-dynamodb.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/aws-dynamodb.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/aws-dynamodb.mdВручную: положить файлы
.clinerules/aws-dynamodb.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Вопросы о aws-dynamodb
Как установить aws-dynamodb в Cursor?
Создайте файл .cursor/rules/aws-dynamodb.mdc в корне проекта и сохраните в него текст правила.
Что делает правило aws-dynamodb?
Оно направляет Cursor на генерацию TypeScript-кода для AWS SDK v3 с паттерном single-table design и изолированным слоем доступа к данным.
Какой режим биллинга DynamoDB рекомендует это правило?
Для непредсказуемой нагрузки правило предписывает PAY_PER_REQUEST (On-Demand), а для стабильного трафика — PROVISIONED с обязательным автоскейлингом.
Исходный текст
aws-dynamodb.mdc · CC0-1.0
---
description: Provides definitive best practices and actionable code examples for interacting with AWS DynamoDB using the AWS SDK v3, focusing on data modeling, performance, security, and common pitfalls.
globs: **/*
---
# aws-dynamodb Best Practices
This guide outlines the definitive best practices for interacting with AWS DynamoDB, ensuring optimal performance, security, and maintainability. We leverage AWS SDK v3, modern data modeling, and infrastructure-as-code principles.
## 1. Data Modeling: Single-Table Design is King
Embrace single-table design to minimize operational overhead and maximize query flexibility. Only use Global Secondary Indexes (GSIs) when your access patterns *cannot* be satisfied by the primary key.
### ✅ GOOD: Single-Table Design with Composite Primary Keys
Model your primary key (Partition Key + Sort Key) to serve your most frequent access patterns. Use generic attribute names like `PK` and `SK` to allow for diverse item types within the same table.
```typescript
// Example: User and Order data in a single table
// PK: USER#<userId>, SK: #METADATA (for user details)
// PK: USER#<userId>, SK: ORDER#<orderId> (for user's orders)
interface UserItem {
PK: string; // e.g., USER#123
SK: string; // e.g., #METADATA
userId: string;
username: string;
email: string;
}
interface OrderItem {
PK: string; // e.g., USER#123
SK: string; // e.g., ORDER#abc-123
orderId: string;
userId: string;
orderDate: string;
totalAmount: number;
}
// Access Pattern: Get User by userId -> Query: PK = 'USER#<userId>', SK = '#METADATA'
// Access Pattern: Get all Orders for a User -> Query: PK = 'USER#<userId>', SK begins_with 'ORDER#'
```
### ❌ BAD: Multi-Table Design for Related Entities
Creating separate tables for every entity type (e.g., `UsersTable`, `OrdersTable`) leads to increased operational complexity and often requires more complex cross-table queries or application-level joins.
```typescript
// Don't do this unless absolutely necessary for strict isolation
// UsersTable: PK = userId
// OrdersTable: PK = orderId, GSI on userId
```
## 2. Code Organization and Structure
Organize your DynamoDB interactions into dedicated data access layers (DALs) or repositories. Use the AWS SDK v3's modular clients and `async/await`.
### ✅ GOOD: Dedicated Data Access Layer with Typed Clients
Encapsulate all DynamoDB operations, ensuring consistent error handling, logging, and parameter construction. Use the DocumentClient for simpler JSON interaction.
```typescript
// src/data/userRepository.ts
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand, PutCommand } from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({ region: process.env.AWS_REGION });
const ddbDocClient = DynamoDBDocumentClient.from(client);
const TABLE_NAME = process.env.DYNAMODB_TABLE_NAME || "YourAppTable";
export class UserRepository {
static async getUserById(userId: string): Promise<UserItem | undefined> {
const params = {
TableName: TABLE_NAME,
Key: { PK: `USER#${userId}`, SK: '#METADATA' },
};
const { Item } = await ddbDocClient.send(new GetCommand(params));
return Item as UserItem | undefined;
}
}
```
### ❌ BAD: Inline DynamoDB Calls or Generic Clients
Avoid scattering DynamoDB logic throughout your application or using untyped, generic clients. This makes maintenance, testing, and refactoring extremely difficult.
```typescript
// src/handlers/createUser.ts - Bad practice
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({});
const ddbDocClient = DynamoDBDocumentClient.from(client);
export const handler = async (event: any) => {
// ...
await ddbDocClient.send(new PutCommand({
TableName: "MyHardcodedTable", // Hardcoded table name
Item: { PK: `USER#${event.userId}`, SK: '#METADATA', /* ... */ },
}));
};
```
## 3. Performance Considerations
Optimize for read/write capacity, minimize data transfer, and leverage eventual consistency where appropriate.
### ✅ GOOD: Use On-Demand Capacity or Provisioned with Auto-Scaling
Choose `ON_DEMAND` for unpredictable workloads. For predictable traffic, use `PROVISIONED` with `AutoScaling` to manage costs and performance.
```yaml
# CloudFormation (example)
Resources:
MyDynamoDBTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${Environment}-MyTable-v1"
AttributeDefinitions:
- AttributeName: PK
AttributeType: S
- AttributeName: SK
AttributeType: S
KeySchema:
- AttributeName: PK
KeyType: HASH
- AttributeName: SK
KeyType: RANGE
BillingMode: PAY_PER_REQUEST # ON_DEMAND is default for new tables
PointInTimeRecoverySpecification: { PointInTimeRecoveryEnabled: true }
SSESpecification: { SSEEnabled: true } # Encryption at rest
```
### ❌ BAD: Fixed Provisioned Capacity for Spiky Workloads
Manually setting fixed provisioned capacity for unpredictable workloads leads to either throttling (under-provisioned) or wasted cost (over-provisioned).
```yaml
# CloudFormation (example of bad practice for spiky workloads)
Resources:
MyDynamoDBTable:
Type: AWS::DynamoDB::Table
Properties:
# ...
BillingMode: PROVISIONED
ProvisionedThroughput:
ReadCapacityUnits: 10 # Fixed, will throttle or waste money
WriteCapacityUnits: 10 # Fixed, will throttle or waste money
```
### ✅ GOOD: Leverage `Query` and `GetItem` with Strong Typing
`GetItem` for single item retrieval by primary key. `Query` for items with the same partition key and an optional sort key condition. Always use `ConsistentRead:
© sanjeed5 · CC0-1.0 · sanjeed5/awesome-cursor-rules-mdc