DynamoDB single-table design using dynamodb-toolbox v2. Use when creating entities, defining key patterns, designing GSIs, writing queries, implementing pagination, or working with any DynamoDB data layer in TypeScript projects.
Ships in typescript. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Inspect the owning package and existing implementation first. Reuse established project types, helpers, errors, lifecycle behavior, and test utilities. The patterns below are options, not an implementation checklist. Introduce one only when the current task requires it.
Type-safe DynamoDB interactions with Entity and Table abstractions for single-table design.
fromRequest, fromItem, and toItem.
Use type-only FormattedItem and InputItem imports instead of handwritten
item mirrors.strict: true.dynamodb-toolbox with its peer dependencies, @aws-sdk/client-dynamodb and @aws-sdk/lib-dynamodb.Table a DynamoDBDocumentClient through documentClient (or assign it before sending commands). Configure removeUndefinedValues: true when records may contain optional fields.entityAttributeName and entityAttributeHidden with entityAttribute: { name, hidden }. Keep it enabled for single-table designs; use entityAttribute: false only for independently queried entity-per-table data.entityAttributeSavedAs on the Table, not the Entity; it must be identical for every entity in a shared table..freeze(). Call .check() only when validating a standalone schema; new Entity(...) already checks its schema.item(...) for root entity schemas, or pass a map(...) schema directly. schema and s replace the former attr shorthands.parse/format with encode/decode, ReadItem with DecodedItem, and ReadValue with DecodedValue..name reads with .entityName and .tableName..partial() when missing enum keys are valid.✓ Use when:
✗ Avoid when:
DynamoDB inverts the relational paradigm: design for known access patterns, not flexible querying.
Before implementing:
See references/modeling.md for detailed methodology.
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'
import { Table } from 'dynamodb-toolbox/table'
const documentClient = DynamoDBDocumentClient.from(new DynamoDBClient(), {
marshallOptions: { removeUndefinedValues: true },
})
const AppTable = new Table({
name: process.env.TABLE_NAME || "AppTable",
documentClient,
partitionKey: { name: "PK", type: "string" },
sortKey: { name: "SK", type: "string" },
indexes: {
GSI1: {
type: "global",
partitionKey: { name: "GSI1PK", type: "string" },
sortKey: { name: "GSI1SK", type: "string" },
},
GSI2: {
type: "global",
partitionKey: { name: "GSI2PK", type: "string" },
sortKey: { name: "GSI2SK", type: "string" },
},
GSI3: {
type: "global",
partitionKey: { name: "GSI3PK", type: "string" },
sortKey: { name: "GSI3SK", type: "string" },
},
},
entityAttributeSavedAs: "_et", // shared by every entity in this table
});
| Index | Purpose |
|---|---|
| Main Table (PK/SK) | Primary entity access |
| GSI1 | Collection queries (issues by repo, members by org) |
| GSI2 | Entity-specific queries and relationships (forks) |
| GSI3 | Hierarchical queries with temporal sorting (repos by owner) |
import { Entity } from 'dynamodb-toolbox/entity'
import { item } from 'dynamodb-toolbox/schema/item'
import { boolean } from 'dynamodb-toolbox/schema/boolean'
import { string } from 'dynamodb-toolbox/schema/string'
const UserEntity = new Entity({
name: "USER",
table: AppTable,
schema: item({
// Business attributes
username: string().required().key(),
email: string().required(),
bio: string().optional(),
}).and(_schema => ({
// Computed keys (PK/SK/GSI keys derived from business attributes)
PK: string().key().link<typeof _schema>(
({ username }) => `ACCOUNT#${username}`
),
SK: string().key().link<typeof _schema>(
({ username }) => `ACCOUNT#${username}`
),
GSI1PK: string().link<typeof _schema>(
({ username }) => `ACCOUNT#${username}`
),
GSI1SK: string().link<typeof _schema>(
({ username }) => `ACCOUNT#${username}`
),
})),
});
const RepoEntity = new Entity({
name: "REPO",
table: AppTable,
schema: item({
owner: string()
.required()
.validate((value: string) => /^[a-zA-Z0-9_-]+$/.test(value))
.key(),
repo_name: string()
.required()
.validate((value: string) => /^[a-zA-Z0-9_-]+$/.test(value))
.key(),
description: string().optional(),
is_private: boolean().default(false),
}).and(_schema => ({
PK: string().key().link<typeof _schema>(
({ owner, repo_name }) => `REPO#${owner}#${repo_name}`
),
SK: string().key().link<typeof _schema>(
({ owner, repo_name }) => `REPO#${owner}#${repo_name}`
),
// GSI3 for temporal sorting (repos by owner, newest first)
GSI3PK: string().link<typeof _schema>(
({ owner }) => `ACCOUNT#${owner}`
),
GSI3SK: string()
.default(() => `#${new Date().toISOString()}`)
.savedAs("GSI3SK"),
})),
});
| Entity | PK | SK | Purpose |
|---|---|---|---|
| User | ACCOUNT#{username} | ACCOUNT#{username} | Direct access |
| Repository | REPO#{owner}#{name} | REPO#{owner}#{name} | Direct access |
| Issue | ISSUE#{owner}#{repo}#{padded_num} | Same as PK | Direct access + enumeration |
| Comment | REPO#{owner}#{repo} | ISSUE#{padded_num}#COMMENT#{id} | Comments under issue |
| Star | ACCOUNT#{username} | STAR#{owner}#{repo}#{timestamp} | Adjacency list pattern |
Key Pattern Rules:
ENTITY#{id} - Simple identifierPARENT#{id}#CHILD#{id} - HierarchyTYPE#{category}#{identifier} - Categorization#{timestamp} - Temporal sorting (# prefix ensures ordering)import { type InputItem, type FormattedItem } from 'dynamodb-toolbox/entity'
// Type exports
type UserRecord = typeof UserEntity
type UserInput = InputItem<typeof UserEntity> // For writes
type UserFormatted = FormattedItem<typeof UserEntity> // For reads
// Usage in entities
class User {
static fromItem(item: UserFormatted): User { /* ... */ }
toItem(): UserInput { /* ... */ }
}
See references/entity-layer.md for transformation patterns.
import { DeleteItemCommand } from 'dynamodb-toolbox/entity/actions/delete'
import { GetItemCommand } from 'dynamodb-toolbox/entity/actions/get'
import { PutItemCommand } from 'dynamodb-toolbox/entity/actions/put'
class UserRepository {
constructor(private entity: UserRecord) {}
// CREATE with duplicate check
async create(user: User): Promise<User> {
try {
const result = await this.entity
.build(PutItemCommand)
.item(user.toItem())
.options({
condition: { attr: "PK", exists: false }, // Prevent duplicates
})
.send()
return User.fromItem(result.ToolboxItem)
} catch (error) {
if (error instanceof ConditionalCheckFailedException) {
throw new DuplicateEntityError("User", user.username)
}
throw error
}
}
// GET by key
async get(username: string): Promise<User | undefined> {
const result = await this.entity
.build(GetItemCommand)
.key({ username })
.send()
return result.Item ? User.fromItem(result.Item) : undefined
}
// UPDATE with existence check
async update(user: User): Promise<User> {
try {
const result = await this.entity
.build(PutItemCommand)
.item(user.toItem())
.options({
condition: { attr: "PK", exists: true }, // Must exist
})
.send()
return User.fromItem(result.ToolboxItem)
} catch (error) {
if (error instanceof ConditionalCheckFailedException) {
throw new EntityNotFoundError("User", user.username)
}
throw error
}
}
// DELETE
async delete(username: string): Promise<void> {
await this.entity.build(DeleteItemCommand).key({ username }).send()
}
}
See references/error-handling.md for error patterns.
import { QueryCommand } from 'dynamodb-toolbox/table/actions/query'
// List issues for a repository using GSI1
async listIssues(owner: string, repoName: string): Promise<Issue[]> {
const result = await this.table
.build(QueryCommand)
.entities(this.issueEntity)
.query({
partition: `ISSUE#${owner}#${repoName}`,
index: "GSI1",
})
.send()
return result.Items?.map(item => Issue.fromItem(item)) || []
}
Pass every expected entity to .entities(...). When all entities retain the shared internal entity attribute, DynamoDB Toolbox applies an entity filter and formats each returned item by its tag. If legacy items lack the tag, use entityAttrFilter: false only during migration and choose an explicit unmatched-item policy:
const { Items } = await AppTable
.build(QueryCommand)
.entities(UserEntity, RepoEntity)
.query({ partition: `ACCOUNT#${username}` })
.options({
entityAttrFilter: false,
noEntityMatchBehavior: "DISCARD",
})
.send()
Without entity tags, Toolbox tries each entity schema in order, which is slower and can throw for an item that matches none. Do not disable the filter for steady-state single-table data.
// List by status using beginsWith on SK
async listOpenIssues(owner: string, repoName: string): Promise<Issue[]> {
const result = await this.table
.build(QueryCommand)
.entities(this.issueEntity)
.query({
partition: `ISSUE#${owner}#${repoName}`,
index: "GSI4",
range: {
beginsWith: "ISSUE#OPEN#", // Filter to open issues only
},
})
.send()
return result.Items?.map(item => Issue.fromItem(item)) || []
}
// Encode/decode pagination tokens
function encodePageToken(lastEvaluated?: Record<string, unknown>): string | undefined {
return lastEvaluated
? Buffer.from(JSON.stringify(lastEvaluated)).toString("base64")
: undefined
}
function decodePageToken(token?: string): Record<string, unknown> | undefined {
return token ? JSON.parse(Buffer.from(token, "base64").toString()) : undefined
}
// Query with pagination
async listReposByOwner(owner: string, limit = 50, offset?: string) {
const result = await this.table
.build(QueryCommand)
.entities(this.repoEntity)
.query({
partition: `ACCOUNT#${owner}`,
index: "GSI3",
range: { lt: "ACCOUNT#" }, // Filter to only repos (not account itself)
})
.options({
reverse: true, // Newest first
exclusiveStartKey: decodePageToken(offset), // Continue from cursor
limit,
})
.send()
return {
items: result.Items?.map(item => Repo.fromItem(item)) || [],
nextOffset: encodePageToken(result.LastEvaluatedKey),
}
}
See references/transactions.md for:
PutTransaction + ConditionCheck)$add(1)See references/testing.md for:
Schema:
item({}) for schema definition.key().and().link<typeof _schema>() to compute PK/SK/GSI keys.validate() for field validation.savedAs() when DynamoDB name differs from schema nameTypes:
InputItem<T> for writes (excludes computed attributes)FormattedItem<T> for formatted reads (excludes hidden attributes)DecodedItem<T> when a read must include hidden attributesRepository:
PutItemCommand with { attr: "PK", exists: false } for createsPutItemCommand with { attr: "PK", exists: true } for updatesGetItemCommand with .key() for readsQueryCommand with .entities() for type-safe queriesErrors:
ConditionalCheckFailedException → DuplicateEntityError (create) or EntityNotFoundError (update)Testing:
evals/evals.json (opens in a new tab)references/entity-layer.md (opens in a new tab)references/error-handling.md (opens in a new tab)references/modeling.md (opens in a new tab)references/repository-layer.md (opens in a new tab)references/testing.md (opens in a new tab)references/transactions.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
8 skills in this plugin
/typescript-api-designREST API design patterns. Use when designing endpoints, error responses, pagination, versioning, or API structure. Framework-agnostic principles for building consistent, maintainable APIs./typescript-build-toolsTypeScript project tooling with Bun or pnpm, TypeScript 7, Vitest, Biome or Oxc (Oxlint and Oxfmt), and Turborepo. Use when setting up package.json scripts, running builds, typechecking, configuring tests, linting, formatting, or orchestrating monorepo development./typescript-drizzle-ormType-safe SQL with Drizzle ORM in TypeScript. Use when defining database schemas, writing queries, setting up relations, running migrations, working with PostgreSQL/MySQL/SQLite/Cloudflare D1/Durable Objects data layers, or integrating drizzle-orm/effect-postgres with @effect/sql-pg and Effect Layers.No slash command · from typescript
npx claudepluginhub martinffx/typescript-skills --plugin typescript