electrodb
Use when defining DynamoDB entities, modeling indexes, or writing queries/mutations with the ElectroDB ORM. Covers entity schema, access patterns, CRUD operations, update expressions, and single-table design patterns.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 3
- Forks
- 0
01 前言 Front Matter
- name
- electrodb
- description
- Use when defining DynamoDB entities, modeling indexes, or writing queries/mutations with the ElectroDB ORM. Covers entity schema, access patterns, CRUD operations, update expressions, and single-table design patterns.
02 资源文件 2
- 参考文档evals/evals.json3.0 KB
- 脚本scripts/new-entity.sh3.8 KB
03 SKILL.md 正文
ElectroDB
TypeScript-first DynamoDB ORM. Manages composite key composition, enforces attribute types, and generates safe DocumentClient params. No raw DynamoDBClient calls.
Installation
npm install electrodb @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb
Entity Definition
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
import { Entity } from "electrodb";
const client = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const Task = new Entity(
{
model: {
entity: "task", // item type namespace
service: "taskapp", // application namespace
version: "1",
},
attributes: {
taskId: { type: "string", required: true, default: () => crypto.randomUUID() },
projectId: { type: "string", required: true },
employeeId: { type: "string", required: true },
status: { type: ["pending", "active", "done"] as const, required: true },
description: { type: "string" },
ttl: { type: "number" }, // epoch seconds for DynamoDB TTL
createdAt: { type: "string", readOnly: true, default: () => new Date().toISOString() },
updatedAt: { type: "string", watch: "*", set: () => new Date().toISOString() },
},
indexes: {
// Table index (no `index` property = primary table index)
primary: {
pk: { field: "pk", composite: ["taskId"] },
sk: { field: "sk", composite: ["projectId"] },
},
// GSI — reference by logical name, not DynamoDB index name
byProject: {
index: "gsi1pk-gsi1sk-index",
pk: { field: "gsi1pk", composite: ["projectId"] },
sk: { field: "gsi1sk", composite: ["employeeId", "taskId"] },
},
},
},
{ table: process.env.TABLE_NAME!, client },
);
Schema Quick Reference
Attribute options
| Option | Description |
|---|---|
type |
"string" "number" "boolean" "list" "map" "set" or enum array ["a","b"] |
required |
Throw on put/create if missing |
default |
Static value or () => value factory |
readOnly |
Cannot be changed after creation |
watch: "*" |
Re-run set on every update (useful for updatedAt) |
validate |
Regex or (val) => boolean |
model fields
| Field | Purpose |
|---|---|
model.entity |
Namespaces items on the table; prevents cross-entity key collisions |
model.service |
Groups entities into a Service for cross-entity queries |
model.version |
Bumping changes key format — migrate existing items first |
Index Design
indexes: {
// Primary (table index) — no `index` property
primary: {
pk: { field: "pk", composite: ["tenantId"] },
sk: { field: "sk", composite: ["entityId", "createdAt"] },
},
// GSI
byStatus: {
index: "gsi1pk-gsi1sk-index",
pk: { field: "gsi1pk", composite: ["tenantId", "status"] },
sk: { field: "gsi1sk", composite: ["createdAt"] },
},
// LSI (same pk field as table index)
byDate: {
index: "lsi1-index",
pk: { field: "pk", composite: ["tenantId"] },
sk: { field: "lsi1sk", composite: ["createdAt"] },
},
}
Key composition rule: composite array order is hierarchical — you can query on a prefix but not skip attributes. ["a","b","c"] supports queries on a or a+b or a+b+c, never b alone.
CRUD Operations
All operations are lazy — chain methods build the expression, then call .go() to execute or .params() to inspect the raw DocumentClient params.
put (full overwrite)
const { data } = await Task.put({
taskId: "t-001",
projectId: "proj-x",
employeeId: "emp-42",
status: "pending",
}).go();
create (fails if item exists)
await Task.create({ taskId, projectId, employeeId, status: "pending" }).go();
get
const { data } = await Task.get({ taskId: "t-001", projectId: "proj-x" }).go();
// data is null if not found
delete
await Task.delete({ taskId: "t-001", projectId: "proj-x" }).go();
update
// Chain operations
await Task.update({ taskId, projectId })
.set({ status: "active", description: "started" })
.go();
// data() for type-safe complex updates
await Task.update({ taskId, projectId })
.data((a, o) => {
o.set(a.status, "done");
o.remove(a.description);
o.add(a.retryCount, 1); // increment number
o.append(a.log, ["step complete"]); // append to list
})
.go();
patch (update + fails if item missing)
await Task.patch({ taskId, projectId }).set({ status: "done" }).go();
Queries
// By primary index — pk composite only
const { data } = await Task.query.primary({ taskId: "t-001" }).go();
// By GSI — filter sk with begins/between/gte/lte
const { data } = await Task.query.byProject({ projectId: "proj-x" })
.begins({ employeeId: "emp-" })
.go();
// Sort descending, limit, paginate
const { data, cursor } = await Task.query.byProject({ projectId: "proj-x" })
.go({ order: "desc", limit: 20 });
// Next page
const { data: page2 } = await Task.query.byProject({ projectId: "proj-x" })
.go({ cursor });
Sort key operations
| Method | DynamoDB equivalent |
|---|---|
.begins({ sk: "val" }) |
begins_with |
.between({ sk: "a" }, { sk: "z" }) |
BETWEEN |
.gte({ sk: "val" }) |
>= val |
.gt({ sk: "val" }) |
> val |
.lte({ sk: "val" }) |
<= val |
.lt({ sk: "val" }) |
< val |
Filter (post-query)
const { data } = await Task.query.byProject({ projectId })
.where((attr, op) => op.eq(attr.status, "pending"))
.go();
// Multiple conditions
.where((attr, op) => `${op.eq(attr.status, "pending")} AND ${op.gt(attr.ttl, 0)}`)
Conditional Writes
// Conditional update — fail if condition not met
await Task.update({ taskId, projectId })
.set({ status: "done" })
.where((attr, op) => op.eq(attr.status, "active"))
.go();
Execution Options
// Inspect params without executing
const params = Task.get({ taskId, projectId }).params();
// Override table at runtime
await Task.get({ taskId, projectId }).go({ table: "other-table" });
// Include pk/sk in response (stripped by default)
await Task.get({ taskId, projectId }).go({ data: "includeKeys" });
// Consistent read
await Task.get({ taskId, projectId }).go({ consistent: true });
// Project specific attributes
await Task.get({ taskId, projectId }).go({ attributes: ["status", "createdAt"] });
Single-Table Design Patterns
One table, generic key names — ElectroDB namespaces items by model.entity automatically. Items from different entities on the same table never collide.
TTL — declare as { type: "number" } attribute, enable TTL on the field in DynamoDB console/CDK. Set epoch-seconds value at write time.
const ttl = Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 7; // 7 days
await Task.put({ ...attrs, ttl }).go();
Service — group multiple Entity objects for cross-entity queries:
import { Service } from "electrodb";
const AppService = new Service({ Task, Employee });
// AppService.collections.<collectionName>(...).go()
Common Mistakes
| Mistake | Fix |
|---|---|
| Querying a partial composite pk | All pk composites required; sk composites are optional prefix |
Using update on non-existent item |
Use patch to get ConditionalCheckFailed or upsert |
Forgetting .go() |
Expressions are lazy — nothing executes without .go() |
Raw DynamoDBClient for DynamoDB ops |
Always use entity methods; raw client bypasses type safety |
Bumping model.version without migration |
Changes key format — old items become invisible |
set on a readOnly attribute |
Throws at runtime; set defaults only via default |
Additional resources
scripts/new-entity.sh <EntityName>— scaffoldssrc/entities/<entity-name>.entity.tswith a ready-to-editnew Entity({...})skeleton (model namespace,createdAt/updatedAt/ttlattributes, a primarypk/skcomposite index, and one GSI). Derives a kebab-case filename and a PascalCase export from the argument, and never overwrites an existing file. Use it to start a new entity instead of hand-copying the boilerplate above.
04 同仓库更多 Skills
designing-in-patterns
Use when designing, planning or auditing UI against a component library — naming surfaces with the repo's pattern vocabulary, deciding reuse versus extend versus new, exploring compositions, or writing the reuse table (component-plan.md, a spec's `## Reuse`, a UI audit). Carries the design method; the repo's own vocabulary, bundle and board rules come from project-context and the designer override.
typeorm
Use when defining TypeORM entities, writing migrations, or building repository/query-builder code in TypeScript. Covers entity and relation decorators, the Data Mapper pattern, migrations, the query builder, transactions, and multi-database configuration.
hono-api
Use when building or extending REST APIs with Hono + @hono/zod-openapi. Covers schema-first route declaration with createRoute, feature-grouped composable routers, a class-based service layer behind interfaces, the strategy pattern for multi-event webhooks, typed request validation, and auto-generated OpenAPI docs.
atomic-design
Use when structuring or decomposing any frontend UI into reusable components, regardless of framework. Applies Brad Frost's atomic design methodology — atoms, molecules, organisms, templates, and pages — to guide consistent component hierarchy, naming, and composition decisions.
writing-docs
Use when writing, restructuring, or reviewing any prose documentation — a tutorial, how-to guide, reference page, or explanation/conceptual doc — for a public docs site (e.g. Mintlify MDX, docs/, README material), a getting-started guide, an API/CLI reference page, or a "why we built it this way" conceptual page. Applies the Diátaxis framework (see https://diataxis.fr/) — every document belongs to exactly one of the four quadrants (tutorial / how-to guide / reference / explanation), and mixing quadrants inside one document is the single most common documentation failure. Covers the four-quadrant compass for picking the right form, per-quadrant structure templates, an anti-pattern list for quadrant drift, and generic voice/craft rules — repo-specific voice and target output format (e.g. Mintlify MDX) are resolved from the repo's docs-manifest (falling back to project-context), never hardcoded here.
writing-adrs
Use when authoring an Architecture Decision Record (ADR) — a short document that captures one significant, hard-to-reverse technical or architectural decision, its context, and its consequences. Triggered by the sdlc ADR pipeline (the knowledge-engineer agent behind /sdlc:docs seed adr and /sdlc:docs distill) when generating an ADR from a story, and by anyone hand-authoring an ADR under docs/adr/ today. Covers why ADRs are kept short and inverted-pyramid, the required sections (Title, Status, Decision, Context, Alternatives Considered, Consequences), the proposed→accepted→superseded (or →rejected) status lifecycle and the never-edit-only-supersede immutability rule, the NNNN-decision-slug.md filename convention, and the ADR frontmatter fields (status, agents, source-stories) the pipeline reads to route a generated ADR into docs/adr/index.md.