DynamoDB-Toolbox v2 Patterns (TypeScript)
Overview
This skill provides practical TypeScript patterns for using DynamoDB-Toolbox v2 with AWS SDK v3 DocumentClient. It focuses on type-safe schema modeling, .build() command usage, and production-ready single-table design.
When to Use
- Defining DynamoDB tables and entities with strict TypeScript inference
- Modeling schemas with
item, string, number, list, set, map, and record
- Implementing
GetItem, PutItem, UpdateItem, DeleteItem via .build()
- Building query and scan access paths with primary keys and GSIs
- Handling batch and transactional operations
- Designing single-table systems with computed keys and entity patterns
Instructions
- Start from access patterns: identify read/write queries first, then design keys.
- Create table + entity boundaries: one table, multiple entities if using single-table design.
- Define schemas with constraints: apply
.key(), .required(), .default(), .transform(), .link().
- Use
.build() commands everywhere: avoid ad-hoc command construction for consistency and type safety.
- Add query/index coverage: validate GSI/LSI paths for each required access pattern.
- Use batch/transactions intentionally: batch for throughput, transactions for atomicity.
- Keep items evolvable: use optional fields, defaults, and derived attributes for schema evolution.
Examples
Install and Setup
npm install dynamodb-toolbox @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
import { Table } from 'dynamodb-toolbox/table';
import { Entity } from 'dynamodb-toolbox/entity';
import { item, string, number, list, map } from 'dynamodb-toolbox/schema';
const client = new DynamoDBClient({ region: process.env.AWS_REGION ?? 'eu-west-1' });
const documentClient = DynamoDBDocumentClient.from(client);
export const AppTable = new Table({
name: 'app-single-table',
partitionKey: { name: 'PK', type: 'string' },
sortKey: { name: 'SK', type: 'string' },
indexes: {
byType: { type: 'global', partitionKey: { name: 'GSI1PK', type: 'string' }, sortKey: { name: 'GSI1SK', type: 'string' } }
},
documentClient
});
Entity Schema with Modifiers and Complex Attributes
const now = () => new Date().toISOString();
export const UserEntity = new Entity({
name: 'User',
table: AppTable,
schema: item({
tenantId: string().required('always'),
userId: string().required('always'),
email: string().required('always').transform(input => input.toLowerCase()),
role: string().enum('admin', 'member').default('member'),
loginCount: number().default(0),
tags: list(string()).default([]),
profile: map({
displayName: string().optional(),
timezone: string().default('UTC')
}).default({ timezone: 'UTC' })
}),
computeKey: ({ tenantId, userId }) => ({
PK: `TENANT#${tenantId}`,
SK: `USER#${userId}`,
GSI1PK: `TENANT#${tenantId}#TYPE#USER`,
GSI1SK: `EMAIL#${userId}`
})
});
.build() CRUD Commands
import { PutItemCommand } from 'dynamodb-toolbox/entity/actions/put';
import { GetItemCommand } from 'dynamodb-toolbox/entity/actions/get';
import { UpdateItemCommand, $add } from 'dynamodb-toolbox/entity/actions/update';
import { DeleteItemCommand } from 'dynamodb-toolbox/entity/actions/delete';
await UserEntity.build(PutItemCommand)
.item({ tenantId: 't1', userId: 'u1', email: 'A@Example.com' })
.send();
const { Item } = await UserEntity.build(GetItemCommand)
.key({ tenantId: 't1', userId: 'u1' })
.send();
await UserEntity.build(UpdateItemCommand)
.item({ tenantId: 't1', userId: 'u1', loginCount: $add(1) })
.send();
await UserEntity.build(DeleteItemCommand)
.key({ tenantId: 't1', userId: 'u1' })
.send();
Query and Scan Patterns
import { QueryCommand } from 'dynamodb-toolbox/table/actions/query';
import { ScanCommand } from 'dynamodb-toolbox/table/actions/scan';
const byTenant = await AppTable.build(QueryCommand)
.query({
partition: `TENANT#t1`,
range: { beginsWith: 'USER#' }
})
.send();
const byTypeIndex = await AppTable.build(QueryCommand)
.query({
index: 'byType',
partition: 'TENANT#t1#TYPE#USER'
})
.options({ limit: 25 })
.send();
const scanned = await AppTable.build(ScanCommand)
.options({ limit: 100 })
.send();
Batch and Transaction Workflows
import { BatchWriteCommand } from 'dynamodb-toolbox/table/actions/batchWrite';
import { TransactWriteCommand } from 'dynamodb-toolbox/table/actions/transactWrite';
await AppTable.build(BatchWriteCommand)
.requests(
UserEntity.build(PutItemCommand).item({ tenantId: 't1', userId: 'u2', email: 'u2@example.com' }),
UserEntity.build(PutItemCommand).item({ tenantId: 't1', userId: 'u3', email: 'u3@example.com' })
)
.send();
await AppTable.build(TransactWriteCommand)
.requests(
UserEntity.build(PutItemCommand).item({ tenantId: 't1', userId: 'u4', email: 'u4@example.com' }),
UserEntity.build(UpdateItemCommand).item({ tenantId: 't1', userId: 'u1', loginCount: $add(1) })
)
.send();
Single-Table Design Guidance
- Model each business concept as an entity with strict schema.
- Keep PK/SK predictable and composable (
TENANT#, USER#, ORDER#).
- Encode access paths into GSI keys, not in-memory filters.
- Prefer append-only timelines for audit/history data.
- Keep hot partitions under control with scoped partitions and sharding where needed.
Best Practices
- Design keys from access patterns first, then derive entity attributes.
- Keep one source of truth for key composition (
computeKey) to avoid drift.
- Use
.options({ consistent: true }) only where strict read-after-write is required.
- Prefer targeted queries over scans for runtime request paths.
- Add conditional expressions for idempotency and optimistic concurrency control.
- Validate batch/transaction size limits before execution to avoid partial failures.
Constraints and Warnings
- DynamoDB-Toolbox v2 relies on AWS SDK v3 DocumentClient integration.
- Avoid table scans in request paths unless explicitly bounded.
- Use conditional writes for concurrency-sensitive updates.
- Transactions are limited and slower than single-item writes; use only for true atomic requirements.
- Validate key design against target throughput before implementation.
References
Primary references curated from Context7 are available in:
references/api-dynamodb-toolbox-v2.md
1---2name: dynamodb-toolbox-patterns3description: Provides TypeScript patterns for DynamoDB-Toolbox v2 including schema/table/entity modeling, .build() command workflow, query/scan access patterns, batch and transaction operations, and single-table design with computed keys. Use when implementing type-safe DynamoDB access layers with DynamoDB-Toolbox v2 in TypeScript services or serverless applications.4allowed-tools: Read, Write, Edit, Glob, Grep, Bash5metadata:6 source: https://skillmd.com/skills/levalencia/dynamodb-toolbox-patterns7---89# DynamoDB-Toolbox v2 Patterns (TypeScript)1011## Overview1213This skill provides practical TypeScript patterns for using DynamoDB-Toolbox v2 with AWS SDK v3 DocumentClient. It focuses on type-safe schema modeling, `.build()` command usage, and production-ready single-table design.1415## When to Use1617- Defining DynamoDB tables and entities with strict TypeScript inference18- Modeling schemas with `item`, `string`, `number`, `list`, `set`, `map`, and `record`19- Implementing `GetItem`, `PutItem`, `UpdateItem`, `DeleteItem` via `.build()`20- Building query and scan access paths with primary keys and GSIs21- Handling batch and transactional operations22- Designing single-table systems with computed keys and entity patterns2324## Instructions25261. **Start from access patterns**: identify read/write queries first, then design keys.272. **Create table + entity boundaries**: one table, multiple entities if using single-table design.283. **Define schemas with constraints**: apply `.key()`, `.required()`, `.default()`, `.transform()`, `.link()`.294. **Use `.build()` commands everywhere**: avoid ad-hoc command construction for consistency and type safety.305. **Add query/index coverage**: validate GSI/LSI paths for each required access pattern.316. **Use batch/transactions intentionally**: batch for throughput, transactions for atomicity.327. **Keep items evolvable**: use optional fields, defaults, and derived attributes for schema evolution.3334## Examples3536### Install and Setup3738```bash39npm install dynamodb-toolbox @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb40```4142```typescript43import { DynamoDBClient } from '@aws-sdk/client-dynamodb';44import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';45import { Table } from 'dynamodb-toolbox/table';46import { Entity } from 'dynamodb-toolbox/entity';47import { item, string, number, list, map } from 'dynamodb-toolbox/schema';4849const client = new DynamoDBClient({ region: process.env.AWS_REGION ?? 'eu-west-1' });50const documentClient = DynamoDBDocumentClient.from(client);5152export const AppTable = new Table({53 name: 'app-single-table',54 partitionKey: { name: 'PK', type: 'string' },55 sortKey: { name: 'SK', type: 'string' },56 indexes: {57 byType: { type: 'global', partitionKey: { name: 'GSI1PK', type: 'string' }, sortKey: { name: 'GSI1SK', type: 'string' } }58 },59 documentClient60});61```6263### Entity Schema with Modifiers and Complex Attributes6465```typescript66const now = () => new Date().toISOString();6768export const UserEntity = new Entity({69 name: 'User',70 table: AppTable,71 schema: item({72 tenantId: string().required('always'),73 userId: string().required('always'),74 email: string().required('always').transform(input => input.toLowerCase()),75 role: string().enum('admin', 'member').default('member'),76 loginCount: number().default(0),77 tags: list(string()).default([]),78 profile: map({79 displayName: string().optional(),80 timezone: string().default('UTC')81 }).default({ timezone: 'UTC' })82 }),83 computeKey: ({ tenantId, userId }) => ({84 PK: `TENANT#${tenantId}`,85 SK: `USER#${userId}`,86 GSI1PK: `TENANT#${tenantId}#TYPE#USER`,87 GSI1SK: `EMAIL#${userId}`88 })89});90```9192### `.build()` CRUD Commands9394```typescript95import { PutItemCommand } from 'dynamodb-toolbox/entity/actions/put';96import { GetItemCommand } from 'dynamodb-toolbox/entity/actions/get';97import { UpdateItemCommand, $add } from 'dynamodb-toolbox/entity/actions/update';98import { DeleteItemCommand } from 'dynamodb-toolbox/entity/actions/delete';99100await UserEntity.build(PutItemCommand)101 .item({ tenantId: 't1', userId: 'u1', email: 'A@Example.com' })102 .send();103104const { Item } = await UserEntity.build(GetItemCommand)105 .key({ tenantId: 't1', userId: 'u1' })106 .send();107108await UserEntity.build(UpdateItemCommand)109 .item({ tenantId: 't1', userId: 'u1', loginCount: $add(1) })110 .send();111112await UserEntity.build(DeleteItemCommand)113 .key({ tenantId: 't1', userId: 'u1' })114 .send();115```116117### Query and Scan Patterns118119```typescript120import { QueryCommand } from 'dynamodb-toolbox/table/actions/query';121import { ScanCommand } from 'dynamodb-toolbox/table/actions/scan';122123const byTenant = await AppTable.build(QueryCommand)124 .query({125 partition: `TENANT#t1`,126 range: { beginsWith: 'USER#' }127 })128 .send();129130const byTypeIndex = await AppTable.build(QueryCommand)131 .query({132 index: 'byType',133 partition: 'TENANT#t1#TYPE#USER'134 })135 .options({ limit: 25 })136 .send();137138const scanned = await AppTable.build(ScanCommand)139 .options({ limit: 100 })140 .send();141```142143### Batch and Transaction Workflows144145```typescript146import { BatchWriteCommand } from 'dynamodb-toolbox/table/actions/batchWrite';147import { TransactWriteCommand } from 'dynamodb-toolbox/table/actions/transactWrite';148149await AppTable.build(BatchWriteCommand)150 .requests(151 UserEntity.build(PutItemCommand).item({ tenantId: 't1', userId: 'u2', email: 'u2@example.com' }),152 UserEntity.build(PutItemCommand).item({ tenantId: 't1', userId: 'u3', email: 'u3@example.com' })153 )154 .send();155156await AppTable.build(TransactWriteCommand)157 .requests(158 UserEntity.build(PutItemCommand).item({ tenantId: 't1', userId: 'u4', email: 'u4@example.com' }),159 UserEntity.build(UpdateItemCommand).item({ tenantId: 't1', userId: 'u1', loginCount: $add(1) })160 )161 .send();162```163164## Single-Table Design Guidance165166- Model each business concept as an entity with strict schema.167- Keep PK/SK predictable and composable (`TENANT#`, `USER#`, `ORDER#`).168- Encode access paths into GSI keys, not in-memory filters.169- Prefer append-only timelines for audit/history data.170- Keep hot partitions under control with scoped partitions and sharding where needed.171172## Best Practices173174- Design keys from access patterns first, then derive entity attributes.175- Keep one source of truth for key composition (`computeKey`) to avoid drift.176- Use `.options({ consistent: true })` only where strict read-after-write is required.177- Prefer targeted queries over scans for runtime request paths.178- Add conditional expressions for idempotency and optimistic concurrency control.179- Validate batch/transaction size limits before execution to avoid partial failures.180181## Constraints and Warnings182183- DynamoDB-Toolbox v2 relies on AWS SDK v3 DocumentClient integration.184- Avoid table scans in request paths unless explicitly bounded.185- Use conditional writes for concurrency-sensitive updates.186- Transactions are limited and slower than single-item writes; use only for true atomic requirements.187- Validate key design against target throughput before implementation.188189## References190191Primary references curated from Context7 are available in:192193- `references/api-dynamodb-toolbox-v2.md`