dynamodb-toolbox
dynamodb-toolbox copied to clipboard
Unable to convert date string to JS Date instance
I have a field which represents an ISO 8601 timestamp (aside from created/update timestamps) which I want to be able to handle as a Date object (due to making several comparison once the entity has been read from the DB.
It seems that the entity type doesn't infer the actual type from either format
or default
, which could return something other than the attributes type of 'string'
.
I see from the docs that you can override the action call or the Entity with the correct shape - an 'Overlay' - (which also effectively disables automatic type inference.
const SensorEntity = new Entity({
name: 'Sensor',
attributes: {
devEUI: { type: 'string', partitionKey: true },
sensorId: { type: 'number', sortKey: true },
lastCompliance: { type: 'string', format: (v: string) => new Date(v), transform: (v: Date) => v.toISOString() },
},
table: MyTable
} as const)
Original code:
const { Item: sensor } = SensorEntity.get({ devEUI: 'XXX', sensorId: 0})
console.log(typeof sensor.lastCompliance) // string
With overlay:
const { Item: sensor } = SensorEntity.get<EntityItem<SensorEntity> & { lastCompliance: Date }>({ devEUI: 'XXX', sensorId: 0})
console.log(sensor.lastCompliance instanceof Date) // true
However, the IDE's (Jetbrains) type inference seems to show an expanded version of Date which cannot them be assigned to a Date
Type as inferred:
Attempt to assign:
The same happens if I try to do the same on Entity.
It also seems to mess up put
calls.
It seems to be something about Date as a plain JS object seems to be interpretted correctly.