awslabs / dynamodb-data-mapper-js

A schema-based data mapper for Amazon DynamoDB.
https://awslabs.github.io/dynamodb-data-mapper-js/
Apache License 2.0
817 stars 106 forks source link

Model property that is both sort and range key #173

Open jonterry-sans opened 4 years ago

jonterry-sans commented 4 years ago

Looking for suggestions on how best to accomplish defining a model property that is both the partion/hash key as well as the sort/range key.

  @hashKey({
    attributeName: "partitionKey",
    defaultProvider: (): string => `record#${uuid.v4}`
  })
  @rangeKey({
    attributeName: "sortKey"
  })
  id!: string;

Due to a table design i need to duplicate an ID across both the Partition and Sort key on my table. Ideally this would leverage a default provider, and only shown as a single property on the model. Does anyone have any suggestions or thoughts regarding an implementation that would accomplish this. Is it possible to write a custom datamapper annotation to support this design?

jeskew commented 4 years ago

Both hashKey and rangeKey are just thin wrappers around @attribute, so in the example you provide, I believe the @hashKey decorator will override what was specified in the @rangeKey decorator. Targeting the same property with two separate @attribute decorators like that should probably throw to prevent ambiguous situations like this.

The schema used by the mapper is keyed by property name, so to get the schema you want to work, I believe you would need to use one property and one getter that proxies to that property, e.g.,

  @hashKey({
    attributeName: "partitionKey",
    defaultProvider: (): string => `record#${uuid.v4}`
  })
  id!: string;

  @rangeKey()
  get sortKey(): string {
     return this.id;
  }