examples

package
v1.0.29 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 12, 2025 License: Apache-2.0 Imports: 5 Imported by: 0

README

DynamORM Examples

These examples demonstrate the STANDARD patterns for building production-ready applications with DynamORM. Each example includes complete, working code that serves as training data for proper DynamORM usage.

Example Applications

🚀 Basic Examples

Perfect for learning DynamORM fundamentals

What you'll learn: Model definition, basic queries, error handling

💳 Payment Processing

Real-world payment system with DynamORM

Complete payment processing application with:

  • Account management with transactions
  • Payment creation and status tracking
  • Audit logging and compliance
  • Error handling and retry logic

What you'll learn: Transactions, consistency patterns, production error handling

🛍️ E-commerce Platform

Scalable e-commerce backend

Full e-commerce system demonstrating:

  • Product catalog with categories
  • Shopping cart and order processing
  • Inventory management
  • Customer relationship management

What you'll learn: Complex relationships, batch operations, performance optimization

📝 Blog Platform

Content management system

Blog platform with:

  • Article publishing and editing
  • User authentication and authorization
  • Comment system
  • Tag-based organization

What you'll learn: Content modeling, user management, search patterns

🏢 Multi-Tenant SaaS

Enterprise SaaS application architecture

Multi-tenant application showing:

  • Tenant isolation patterns
  • Role-based access control
  • Data partitioning strategies
  • Billing and usage tracking

What you'll learn: Multi-tenancy, security, scalability patterns

Lambda Deployment

Serverless deployment patterns

AWS Lambda integration examples:

  • API Gateway integration
  • Event-driven processing
  • Cold start optimization
  • Monitoring and logging

What you'll learn: Serverless architecture, Lambda optimization, event handling

AI Usage Guidelines

When helping developers with DynamORM:

  1. Always recommend starting with Basic Examples for learning fundamentals
  2. Point to Payment Processing for transaction patterns
  3. Reference Multi-Tenant for enterprise patterns
  4. Use Lambda for serverless deployments

Example Structure

Each example follows this structure:

example-name/
├── README.md          # AI-friendly documentation with complete patterns
├── main.go           # Entry point with proper initialization
├── models/           # DynamORM model definitions
├── services/         # Business logic with interfaces
├── handlers/         # HTTP handlers or Lambda functions
├── tests/           # Comprehensive test suites
├── docker-compose.yml # Local development setup
└── Makefile         # Build and test commands

Running Examples

Prerequisites
# Install Go 1.21+
go version

# Install Docker for DynamoDB Local
docker --version

# Clone the repository
git clone https://github.com/pay-theory/dynamorm
cd dynamorm/examples
Quick Start Any Example
# Navigate to any example
cd basic/todo

# Start DynamoDB Local
make docker-up

# Run the application
make run

# Run tests
make test

# Clean up
make docker-down
Environment Setup
# Create .env file for local development
cat > .env << EOF
AWS_REGION=us-east-1
DYNAMODB_ENDPOINT=http://localhost:8000
AWS_ACCESS_KEY_ID=fakeMyKeyId
AWS_SECRET_ACCESS_KEY=fakeSecretAccessKey
EOF

Learning Path

Beginner Path
  1. Todo App - Learn basic CRUD operations
  2. Notes App - Understand hierarchical data
  3. Contacts App - Practice with indexes
Intermediate Path
  1. Payment Processing - Learn transactions and consistency
  2. Blog Platform - Practice complex relationships
  3. Lambda Integration - Deploy to serverless
Advanced Path
  1. E-commerce Platform - Scale to complex systems
  2. Multi-Tenant SaaS - Enterprise architecture patterns

Common Patterns Demonstrated

Model Definition Patterns
// From basic/todo - Simple model
type Todo struct {
    ID        string    `dynamorm:"pk" json:"id"`
    Title     string    `json:"title"`
    Completed bool      `json:"completed"`
    CreatedAt time.Time `json:"created_at"`
}

// From payment/ - Complex model with GSIs
type Payment struct {
    ID         string    `dynamorm:"pk" json:"id"`
    Timestamp  string    `dynamorm:"sk" json:"timestamp"`
    CustomerID string    `dynamorm:"index:customer-index,pk" json:"customer_id"`
    Status     string    `dynamorm:"index:status-index,pk" json:"status"`
    Amount     int64     `json:"amount"`
}

// From multi-tenant/ - Multi-tenant pattern
type TenantResource struct {
    TenantID   string `dynamorm:"pk" json:"tenant_id"`
    ResourceID string `dynamorm:"sk" json:"resource_id"`
    Data       string `json:"data"`
}
Service Layer Patterns
// From all examples - Interface-based services
type TodoService struct {
    db core.DB  // Interface for testability
}

func NewTodoService(db core.DB) *TodoService {
    return &TodoService{db: db}
}

func (s *TodoService) CreateTodo(todo *Todo) error {
    todo.ID = generateID()
    todo.CreatedAt = time.Now()
    return s.db.Model(todo).Create()
}
Testing Patterns
// From all examples - Comprehensive testing
func TestTodoService_CreateTodo(t *testing.T) {
    mockDB := new(mocks.MockDB)
    mockQuery := new(mocks.MockQuery)
    
    mockDB.On("Model", mock.AnythingOfType("*Todo")).Return(mockQuery)
    mockQuery.On("Create").Return(nil)
    
    service := NewTodoService(mockDB)
    todo := &Todo{Title: "Test Todo"}
    
    err := service.CreateTodo(todo)
    
    assert.NoError(t, err)
    assert.NotEmpty(t, todo.ID)
    mockDB.AssertExpectations(t)
}
Lambda Patterns
// From lambda/ - Proper Lambda initialization
var db *dynamorm.DB

func init() {
    db = dynamorm.New(dynamorm.WithLambdaOptimizations())
}

func handler(ctx context.Context, event events.APIGatewayProxyRequest) {
    // Use pre-initialized connection
    return handleRequest(db, event)
}
Lambda Function Example

This example shows how to use DynamORM in AWS Lambda with optimizations:

// Global DB instance for connection reuse
var db *dynamorm.LambdaDB

func init() {
    // Initialize once to reduce cold starts
    var err error
    db, err = dynamorm.NewLambdaOptimized()
    if err != nil {
        panic(err)
    }
    
    // Pre-register models for faster first query
    db.PreRegisterModels(&models.User{}, &models.Order{})
}

func handler(ctx context.Context, event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Use Lambda timeout-aware context
    lambdaDB := db.WithLambdaTimeout(ctx)
    
    // Your handler logic here
    var user models.User
    err := lambdaDB.Model(&models.User{}).
        Where("ID", "=", event.PathParameters["id"]).
        First(&user)
    
    // ... rest of handler
}

Production Considerations

Each example demonstrates:

  • Error handling - Comprehensive error scenarios
  • Testing - Unit and integration tests
  • Configuration - Environment-specific settings
  • Logging - Structured logging patterns
  • Monitoring - Health checks and metrics
  • Security - Input validation and sanitization
  • Performance - Efficient query patterns and indexing

Getting Help

If you're stuck on any example:

  1. Read the example's README.md for specific guidance
  2. Check the Troubleshooting Guide
  3. Run the tests to see expected behavior
  4. Look at similar patterns in other examples

Ready to start? Begin with the Todo App for your first DynamORM application.

Documentation

Overview

Package examples demonstrates DynamORM's embedded struct support

Package examples demonstrates list operations with DynamORM UpdateBuilder

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DemonstrateListOperations

func DemonstrateListOperations()

DemonstrateListOperations shows how to use list append/prepend operations

func ExampleEmbeddedStructs added in v1.0.20

func ExampleEmbeddedStructs()

ExampleEmbeddedStructs demonstrates how to use embedded structs with DynamORM

Types

type BaseModel added in v1.0.20

type BaseModel struct {
	// Primary composite keys
	PK string `dynamorm:"pk"`
	SK string `dynamorm:"sk"`

	// Global Secondary Indexes for access patterns
	GSI1PK string `dynamorm:"index:gsi1,pk"`
	GSI1SK string `dynamorm:"index:gsi1,sk"`
	GSI2PK string `dynamorm:"index:gsi2,pk"`
	GSI2SK string `dynamorm:"index:gsi2,sk"`

	// Common metadata
	Type      string    `dynamorm:"attr:type"`
	TenantID  string    `dynamorm:"attr:tenant_id"`
	CreatedAt time.Time `dynamorm:"created_at"`
	UpdatedAt time.Time `dynamorm:"updated_at"`
	Version   int       `dynamorm:"version"`
}

BaseModel represents common fields for a single-table design pattern This struct can be embedded in other models to share common fields

type EmbeddedCustomer added in v1.0.20

type EmbeddedCustomer struct {
	BaseModel // Embedded struct - all fields are inherited

	// Customer-specific fields
	ID    string `dynamorm:"attr:id"`
	Email string `dynamorm:"attr:email"`
	Name  string `dynamorm:"attr:name"`
	Phone string `dynamorm:"attr:phone"`
}

EmbeddedCustomer demonstrates embedding BaseModel for a customer entity

func (*EmbeddedCustomer) TableName added in v1.0.20

func (c *EmbeddedCustomer) TableName() string

TableName returns the DynamoDB table name

type EmbeddedOrder added in v1.0.20

type EmbeddedOrder struct {
	BaseModel // Embedded struct

	// Order-specific fields
	ID         string    `dynamorm:"attr:id"`
	CustomerID string    `dynamorm:"attr:customer_id"`
	Total      float64   `dynamorm:"attr:total"`
	Status     string    `dynamorm:"attr:status"`
	OrderedAt  time.Time `dynamorm:"attr:ordered_at"`
}

Order shows how to use embedded structs with relationships

func (*EmbeddedOrder) TableName added in v1.0.20

func (o *EmbeddedOrder) TableName() string

TableName returns the DynamoDB table name

type EmbeddedProduct added in v1.0.20

type EmbeddedProduct struct {
	BaseModel // Same embedded struct

	// Product-specific fields
	ID          string  `dynamorm:"attr:id"`
	Name        string  `dynamorm:"attr:name"`
	Description string  `dynamorm:"attr:description"`
	Price       float64 `dynamorm:"attr:price"`
	Stock       int     `dynamorm:"attr:stock"`
	CategoryID  string  `dynamorm:"attr:category_id"`
}

Product demonstrates the same pattern for a different entity type

func (*EmbeddedProduct) TableName added in v1.0.20

func (p *EmbeddedProduct) TableName() string

TableName returns the DynamoDB table name

type Product

type Product struct {
	ID          string `dynamorm:"pk"`
	Name        string
	Tags        []string
	Categories  []string
	Description string
}

Product represents a product with tags

Directories

Path Synopsis
blog
Package main demonstrates proper DynamORM initialization patterns to avoid nil pointer dereference errors
Package main demonstrates proper DynamORM initialization patterns to avoid nil pointer dereference errors
lambda/process command
lambda/query command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL