CustomMapper

With custom mappers you're able to define how the JS values are mapped (toDb) and how the DynamoDB attributes are parsed (fromDb).

Scenarios when you need a custom mapper:

  • Using objects as partition key or sort key (since DynamoDB only supports [N]umber | [S]tring | [B]inary for such)

  • Working with class instances (non-primitives) instead of plain javascript objects (e.g. Dates)

  • Storing objects in a DynamoDB set (only N|S|B sets are possible)

A mapper for date objects which would be stored as [N]umbers could look like this:

date-to-number.mapper.ts
import { MapperForType, NumberAttribute } from '@shiftcoders/dynamo-easy'

export const dateToNumberMapper: MapperForType<Date, NumberAttribute> = {
  fromDb: attributeValue => new Date(parseInt(attributeValue.N, 10)),
  toDb: propertyValue => ({ N: `${propertyValue.getTime()}` }),
}

Last updated