DynamoDB Toolbox

website·Indexed 32 days ago

https://www.dynamodbtoolbox.com

A light-weight and type-safe library for Amazon DynamoDB. Version v2 provides tools for defining schemas, managing entities, and performing table actions such as query, scan, batch operations, and condition checks, with support for AWS CDK integration.

Tokens
110.3K
Snippets
694
Records
779
Agent score
64%

What's inside DynamoDB Toolbox

  1. Overview of DynamoDB-Toolbox v1

    v1

    DynamoDB-Toolbox is a light-weight, type-safe query builder for DynamoDB and TypeScript. It acts as an abstraction layer over the AWS SDK to simplify the creation of complex DynamoDB requests. Key features include:

    • Data Validation: Validates both pushed and fetched items against defined schemas to ensure data consistency.
    • Rich Schema Syntax: Supports defaults, composition, transformation, and polymorphism.
    • Type-Safety: Provides auto-completion and immediate feedback during development.
    • Single-Table Design: Simplifies querying multiple entities within a single table, while remaining compatible with multi-table setups.
    • Performance: Tree-shakable and compatible with LLRT (Low Latency Runtime) functions as it has no dependencies.
  2. Overview of DynamoDB-Toolbox v1 Table utility actions

    v1

    DynamoDB-Toolbox v1 provides several utility actions for Tables to assist with schema validation, testing, and API access:

    • PrimaryKeyParser: Validates that a given input respects the Primary Key schema of the Table.
    • TableSpy: Enables spying (mocking) of the provided Table for testing purposes.
    • TableRepository: A utility that exposes all available table actions as methods for easier access.
  3. Overview of DynamoDB-Toolbox Table utility actions

    DynamoDB-Toolbox v2 provides several utility actions for Tables to handle schema validation, AWS CDK integration, and data management. Available utilities include:

    • Registry: A single entry point for Table Entities and AccessPatterns.
    • PrimaryKeyParser: Validates that a given input respects the Table's Primary Key schema.
    • TableSpy: Allows for mocking/spying on the provided Table.
    • TableRepository: Wraps table actions as callable methods.
    • CDKTableV2: Generates AWS CDK TableV2 properties based on the Table configuration.
    • TableDTO: Creates a Data Transfer Object (DTO) for the Table.
  4. Overview of DynamoDB Toolbox

    v0.9
    DynamoDB Toolbox is a set of tools designed to simplify interactions with Amazon DynamoDB and the DocumentClient. Unlike a traditional ORM, it focuses on providing a consistent interface to generate API parameters for operations such as put, get, delete, update, query, scan, batchGet, and batchWrite. It is optimized for Single Table Design but supports multiple tables. Key capabilities include mapping JavaScript objects to DynamoDB entities, validating and coercing types, and automatically generating complex UpdateExpression strings.
  5. Overview of DynamoDB-Toolbox v2 Entity utility actions

    DynamoDB-Toolbox v2 provides several utility actions for Entities to handle validation, expression building, and data transformation:

    • EntityParser: Validates that a given input respects the Entity schema based on a specified mode.
    • ConditionParser: Generates DynamoDB Condition Expressions for conditional writes or filtering Query/Scan results.
    • PathParser: Generates DynamoDB Projection Expressions to filter attributes returned by GetItem, Query, or Scan operations.
    • EntityFormatter: Validates and formats a saved item against the Entity schema.
    • EntitySpy: Allows for spying/mocking the provided Entity.
    • EntityRepository: Wraps all entity actions and exposes them as methods for easier access.
    • EntityDTO: Creates a Data Transfer Object (DTO) for the provided Entity.
  6. Overview of DynamoDB-Toolbox

    DynamoDB-Toolbox is a light-weight, type-safe query builder for DynamoDB and TypeScript. It acts as an abstraction layer over the AWS SDK to simplify the creation of complex DynamoDB requests. Key features include:

    • Data Validation: Validates both pushed and fetched items against schemas to ensure data consistency.
    • Rich Schema Syntax: Supports defaults, composition, transformation, and polymorphism.
    • Portability: Schemas can be imported from or exported to Zod and JSON Schema while preserving type-inference.
    • Single-Table Design: Simplifies querying multiple entities within a single table.
    • Performance: Tree-shakable and compatible with LLRT (Low Latency Runtime) functions as it has no dependencies.
  7. Overview of DynamoDB-Toolbox

    DynamoDB-Toolbox is a lightweight, type-safe abstraction layer over the AWS DynamoDB Document Client. It simplifies the creation of complex DynamoDB requests and ensures data consistency by validating pushed and fetched items against user-defined schemas. Key features include:

    • Type-Safety: Deep integration with TypeScript.
    • Schema Validation: Supports defaults, composition, transformations, and polymorphism.
    • Portability: Schemas can be imported from or exported to Zod and JSON Schema while preserving type-inference.
    • Serverless Optimized: Designed for small bundle sizes with tree-shakable, opt-in features.
  8. Use EntityRepository to simplify DynamoDB entity actions

    v1
    The EntityRepository is a utility action in DynamoDB Toolbox v1 that exposes common entity actions (like get, put, update, and delete) as methods on a repository object. This provides a more concise syntax compared to calling individual commands, although it results in larger bundle sizes because it imports all associated action code. It remains compatible with Spies since it still sends standard commands under the hood.
    import { EntityRepository } from 'dynamodb-toolbox/entity/actions/repository'
    
    const pokemonRepository = PokemonEntity.build(
      EntityRepository
    )
    
    // Sends a PutItemCommand
    await pokemonRepository.put(pokemon)
  9. Use the Registry to centralize Entities and AccessPatterns

    The Registry acts as a single entry point for a Table's Entities and AccessPatterns. It allows you to register multiple entities and access patterns in one place, providing a typed interface to retrieve them by name or use shorthand query methods.
    import { Registry } from 'dynamodb-toolbox/table/actions/registry'
    
    const PokeRegistry = PokeTable.build(Registry)
      .registerEntities(PokemonEntity, TrainerEntity, ...)
      .registerAccessPatterns({ trainers, pokemonsByTrainerId })
    
    // Access an Entity by name
    const pokemonEntity = PokeRegistry.entities.pokemon
    
    // Access an AccessPattern by key
    PokeRegistry.accessPatterns.trainers.query(...)
    
    // Use the .query shorthand
    PokeRegistry.query.trainers(...)
  10. Use EntityRepository for concise entity actions

    The EntityRepository is a utility action that exposes all entity actions as methods on a repository object. While this leads to larger bundle sizes because it imports all action code, it provides a more ergonomic syntax for interacting with DynamoDB entities. It can be used in conjunction with Spies since commands are still sent under the hood.
    import { EntityRepository } from 'dynamodb-toolbox/entity/actions/repository'
    
    const pokemonRepository = PokemonEntity.build(
      EntityRepository
    )
    
    // Sends a PutItemCommand
    await pokemonRepository.put(pokemon)
  11. Access path and schema metadata from a SubSchema

    A SubSchema is a Schema Action that provides metadata about the specific part of the schema located by a Finder. It exposes the original path used for the search and the transformed path used for the actual DynamoDB attribute mapping.
    // Assuming levelSubSchema was retrieved via finder.search()
    
    // Get the actual schema definition (e.g., number())
    const levelSchema = levelSubSchema.schema
    
    // Access the original path as provided in the search
    const originalStrPath = levelSubSchema.formattedPath.strPath
    // => 'evolutions[1].level'
    const originalArrPath = levelSubSchema.formattedPath.arrayPath
    // => ['evolutions', 1, 'level']
    
    // Access the transformed path (mapping to the savedAs attribute name)
    const transformedStrPath = levelSubSchema.transformedPath.strPath
    // => '_e[1].level'
    const transformedArrPath = levelSubSchema.transformedPath.arrayPath
    // => ['_e', 1, 'level']
  12. Use EntitySpy to mock DynamoDB actions for unit testing

    v1
    The EntitySpy allows developers to intercept sendable actions (e.g., GetItemCommand, PutItemCommand) on an Entity. It can be used to stub responses, mock dynamic behavior, and inspect the call history of actions. Non-mocked actions continue to be sent to DynamoDB as usual.
    import { EntitySpy } from 'dynamodb-toolbox/entity/actions/spy'
    import { GetItemCommand } from 'dynamodb-toolbox/entity/actions/get'
    
    // Initialize the spy on an entity
    const entitySpy = PokemonEntity.build(EntitySpy)
    
    // Stub a specific command to resolve with mock data
    entitySpy.on(GetItemCommand).resolve({ Item: pokeMock })
    
    // Execute the action
    const { Item } = await PokemonEntity.build(GetItemCommand)
      .key(key)
      .send()
    
    // Verify the result
    expect(Item).toStrictEqual(pokeMock)
    
    // Inspect call count
    const getCount = entitySpy.sent(GetItemCommand).count()
    expect(getCount).toBe(1)
    
    // Cleanup
    entitySpy.reset()   // Reset call history
    entitySpy.restore()  // Stop spying entirely