Expressions (conditions, update)

For conditions and updates, DynamoDB uses expression statements. We provide functions to build those expressions either in a strictly or a non-typed way.

Condition

Condition Expressions are used for two purposes:

  • pre condition for write operations (delete, put, update) onlyIf(),onlyIfAttribute()

  • filter condition for read operations (query, scan ) where(),whereAttribute()

onlyIfAttribute() and whereAttribute() provide a chainable way to add your conditions, all conditions are combined with and operator:

scanReq
    .whereAttribute('myProp').eq('foo')
    .whereAttribute('otherProp').eq('bar')

to either use not or or operator you need to use the onlyIf() resp. where()methods:

nor-not-and-condition.snippet.ts
import { and, attribute, DynamoStore, not, or } from '@shiftcoders/dynamo-easy'
import { Person } from '../models'

const personStore = new DynamoStore(Person)
personStore.delete('vogelsw')
  .onlyIf(
    or(
      and(
        attribute('myProp').eq('foo'),
        attribute('otherProp').eq('bar')
      ),
      not(
        attribute('otherProp').eq('foo bar')
      ),
    )
  )

For better typings the attribute2 function is provided (only useful for top level properties)

attribute2-condition.snippet.ts
import { attribute2, DynamoStore } from '@shiftcoders/dynamo-easy'
import { Person } from '../models'

const personStore = new DynamoStore(Person)

personStore.delete('volgelsw')
  .onlyIf(
    attribute2(Person, 'yearOfBirth').eq(1958),
    // attributes2 only accepts a propertyName from Person
    // eq only accepts a value of type Person.yearOfBirth (number in this case)
  )

The same methods also exists for all transact operations (used in TransactWriteRequest)

Update

As for condition expressions, there are two ways to define the update expressions for an update request:

the chainable way:

updateReq
    .update('name').set('Werner Vogels')

the not-that-chainy way:

update-expression.snippet.ts
import { DynamoStore, update } from '@shiftcoders/dynamo-easy'
import { Person } from '../models'

const personStore = new DynamoStore(Person)
personStore.update('vogelsw')
  .operations(
    update('name').set('Werner Vogels'),
    update('yearOfBirth').set(1984),
  )

the operations method primarily exists for more flexibility

There also exists the update2(ModelClazz, propertyName) function as equivalent to attribute2() for better typing.

The same methods also exists for TransactUpdate (used in TransactWriteRequest)

Last updated