Skip to content

Expression Examples

This page provides practical examples of expressions for common use cases in TinySystems flows.

HTTP Request Handling

Extract Request Data

json
// Incoming HTTP request
{
  "method": "POST",
  "path": "/api/users/123",
  "headers": {
    "Content-Type": "application/json",
    "Authorization": "Bearer eyJ..."
  },
  "body": {
    "name": "Alice",
    "email": "alice@example.com"
  },
  "queryParams": {
    "format": "json"
  }
}
yaml
# Extract common fields
method: "{{$.method}}"
path: "{{$.path}}"
contentType: "{{$.headers['Content-Type']}}"
authToken: "{{$.headers.Authorization}}"
userName: "{{$.body.name}}"
userEmail: "{{$.body.email}}"
format: "{{$.queryParams.format || 'json'}}"

Build API Response

yaml
# Success response
body: |
  {
    "success": true,
    "data": {
      "id": "{{$.userId}}",
      "name": "{{$.userName}}",
      "createdAt": "{{RFC3339(now())}}"
    }
  }
contentType: "application/json"
statusCode: 200
yaml
# Error response
body: |
  {
    "success": false,
    "error": {
      "code": "{{$.errorCode}}",
      "message": "{{$.errorMessage}}"
    }
  }
contentType: "application/json"
statusCode: {{$.errorCode == 'NOT_FOUND' ? 404 : 400}}

Data Transformation

Flatten Nested Object

json
// Input
{
  "user": {
    "profile": {
      "firstName": "Alice",
      "lastName": "Smith"
    },
    "contact": {
      "email": "alice@example.com",
      "phone": "555-1234"
    }
  }
}
yaml
# Output mapping
firstName: "{{$.user.profile.firstName}}"
lastName: "{{$.user.profile.lastName}}"
email: "{{$.user.contact.email}}"
phone: "{{$.user.contact.phone}}"
fullName: "{{$.user.profile.firstName}} {{$.user.profile.lastName}}"

Restructure Data

json
// Input: array of users
{
  "users": [
    {"id": 1, "name": "Alice", "role": "admin"},
    {"id": 2, "name": "Bob", "role": "user"}
  ]
}
yaml
# Extract first user
admin:
  userId: {{$.users[0].id}}
  userName: "{{$.users[0].name}}"
  isAdmin: {{$.users[0].role == 'admin'}}

Combine Multiple Fields

yaml
# Full address
address: "{{$.street}}, {{$.city}}, {{$.state}} {{$.zip}}"

# Display name with title
displayName: "{{$.title || ''}} {{$.firstName}} {{$.lastName}}"

# URL with parameters
apiUrl: "https://api.example.com/v{{$.version}}/{{$.endpoint}}?key={{$.apiKey}}"

Conditional Logic

Status Mapping

yaml
# Map status codes to labels
statusLabel: "{{$.status == 'active' ? 'Active' : ($.status == 'pending' ? 'Pending Review' : 'Inactive')}}"

# Priority color
priorityColor: "{{$.priority == 'high' ? 'red' : ($.priority == 'medium' ? 'yellow' : 'green')}}"

Feature Flags

yaml
# Enable features based on conditions
showAdvanced: {{$.userRole == 'admin' || $.betaUser == true}}
enableNotifications: {{$.preferences.notifications && $.verified}}

Validation Results

yaml
# Validate input
isValidEmail: {{$.email != '' && len($.email) > 5}}
isValidAge: {{$.age >= 18 && $.age <= 120}}
isValid: {{$.isValidEmail && $.isValidAge}}

# Validation message
validationMessage: "{{$.isValid ? 'OK' : 'Please check your input'}}"

Date and Time

Current Timestamp

yaml
# Current time in various formats
timestamp: "{{now()}}"
isoDate: "{{RFC3339(now())}}"

Date Calculations

yaml
# Add context to timestamps
logEntry: "{{RFC3339(now())}} - {{$.eventType}}: {{$.message}}"

Numeric Operations

Calculations

yaml
# Order totals
subtotal: {{$.price * $.quantity}}
taxAmount: {{$.subtotal * 0.08}}
shippingFee: {{$.subtotal > 100 ? 0 : 9.99}}
total: {{$.subtotal + $.taxAmount + $.shippingFee}}

Formatting

yaml
# Round to 2 decimal places
priceFormatted: "{{round($.price * 100) / 100}}"

# Percentage
percentage: "{{round($.completed / $.total * 100)}}%"

Statistics

yaml
# Count items
itemCount: {{$.items.length}}
hasItems: {{$.items.length > 0}}
isEmpty: {{$.items.length == 0}}

String Operations

Case Conversion

yaml
# Normalize input
normalizedEmail: "{{lower($.email)}}"
titleCase: "{{upper($.name)}}"

Trimming

yaml
# Clean input
cleanInput: "{{trim($.userInput)}}"

Building Strings

yaml
# Email template
emailSubject: "Order {{$.orderId}} Confirmation"
emailBody: "Dear {{$.customerName}},\n\nYour order {{$.orderId}} has been confirmed."

# Log message
logMessage: "[{{RFC3339(now())}}] {{upper($.level)}}: {{$.message}}"

Default Values

Handling Missing Data

yaml
# Provide defaults for optional fields
name: "{{$.name || 'Anonymous'}}"
email: "{{$.email || 'not-provided@example.com'}}"
count: {{$.count || 0}}
items: {{$.items || []}}
settings: {{$.settings || {}}}

Chain of Defaults

yaml
# Try multiple sources
displayName: "{{$.nickname || $.firstName || $.username || 'User'}}"
contactEmail: "{{$.workEmail || $.personalEmail || $.email}}"

Conditional Defaults

yaml
# Default based on condition
timeout: {{$.isProduction ? 30 : 5}}
endpoint: "{{$.env == 'prod' ? 'https://api.example.com' : 'https://staging.api.example.com'}}"

Array Handling

Access Elements

yaml
# First and last
firstItem: "{{$.items[0]}}"
lastItem: "{{$.items[-1]}}"

# Specific index
thirdItem: "{{$.items[2]}}"

Array Properties

yaml
# Length and checks
count: {{$.items.length}}
hasItems: {{$.items.length > 0}}
moreThanFive: {{$.items.length > 5}}

Working with Objects in Arrays

yaml
# First user's email
firstUserEmail: "{{$.users[0].email}}"

# First order total
firstOrderTotal: {{$.orders[0].total}}

Object Construction

Build Response Objects

yaml
response:
  status: "success"
  timestamp: "{{RFC3339(now())}}"
  data:
    userId: "{{$.userId}}"
    userName: "{{$.userName}}"
    isActive: {{$.status == 'active'}}
  meta:
    requestId: "{{$.requestId}}"
    processingTime: {{$.endTime - $.startTime}}

Transform for API

yaml
# Transform internal model to API format
apiUser:
  id: "{{$.userId}}"
  display_name: "{{$.firstName}} {{$.lastName}}"
  email_address: "{{$.email}}"
  is_verified: {{$.verified}}
  created_at: "{{$.createdAt}}"

Webhook Payloads

GitHub Webhook

json
// Incoming GitHub webhook
{
  "action": "opened",
  "pull_request": {
    "number": 123,
    "title": "Add feature",
    "user": {
      "login": "developer"
    }
  },
  "repository": {
    "full_name": "org/repo"
  }
}
yaml
# Extract for notification
eventType: "pull_request"
action: "{{$.action}}"
prNumber: {{$.pull_request.number}}
prTitle: "{{$.pull_request.title}}"
author: "{{$.pull_request.user.login}}"
repo: "{{$.repository.full_name}}"
message: "PR #{{$.pull_request.number}} {{$.action}}: {{$.pull_request.title}} by {{$.pull_request.user.login}}"

Stripe Webhook

json
// Incoming Stripe webhook
{
  "type": "payment_intent.succeeded",
  "data": {
    "object": {
      "id": "pi_123",
      "amount": 2000,
      "currency": "usd",
      "customer": "cus_456"
    }
  }
}
yaml
# Process payment event
eventType: "{{$.type}}"
paymentId: "{{$.data.object.id}}"
amount: {{$.data.object.amount / 100}}
currency: "{{upper($.data.object.currency)}}"
customerId: "{{$.data.object.customer}}"
message: "Payment of ${{$.data.object.amount / 100}} {{upper($.data.object.currency)}} received"

Error Handling

Safe Navigation

yaml
# Handle potentially missing data
userName: "{{$.user != null ? $.user.name : 'Unknown'}}"
email: "{{$.user.email || 'no-email@example.com'}}"

Validation Before Use

yaml
# Check before accessing
hasUser: {{$.user != null}}
userName: "{{$.hasUser ? $.user.name : 'Guest'}}"

Complex Examples

Order Processing

yaml
# Complete order summary
order:
  id: "{{$.orderId}}"
  customer:
    name: "{{$.customer.firstName}} {{$.customer.lastName}}"
    email: "{{$.customer.email}}"
  items:
    count: {{$.items.length}}
    firstItem: "{{$.items[0].name}}"
  totals:
    subtotal: {{$.subtotal}}
    tax: {{round($.subtotal * 0.08 * 100) / 100}}
    shipping: {{$.subtotal > 100 ? 0 : 9.99}}
    total: {{$.subtotal + $.tax + $.shipping}}
  status: "{{$.paid ? 'confirmed' : 'pending'}}"
  timestamp: "{{RFC3339(now())}}"

User Registration

yaml
# Create user record
newUser:
  id: "user_{{now()}}"
  email: "{{lower(trim($.email))}}"
  displayName: "{{$.displayName || $.email}}"
  role: "{{$.inviteCode ? 'member' : 'guest'}}"
  verified: false
  createdAt: "{{RFC3339(now())}}"
  settings:
    notifications: true
    theme: "{{$.prefersDark ? 'dark' : 'light'}}"

Next Steps

Build flow-based applications on Kubernetes