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
816 stars 106 forks source link

How to create a custom mapping for classes #189

Open mariobittencourt opened 4 years ago

mariobittencourt commented 4 years ago

Hi,

I would like to use this package to handle the persistence of some entities in DynamoDB. In my case I have some properties in those entities that are not scalar values themselves and I wonder how can I create a mapper that has custom instructions when saving or restoring that property.

Example:

class Id {
   private value: string;

   private constructor(value: string) {
          this.value = value;
   }

    public static create(value: string) {
         return new Id(value);
    }

   public toString(): string {
     return this.value;
  }
}

class Foo {
      constructor(private readonly id: Id, private readonly name: string) {}
}

So I want to inform the data mapper that it should use the toString to get the representation of Id when persisting any instance of the Foo class, and at the same time when retrieving the a Foo instance it should take the string representation of the Id from Dynamo and call the Id::create.

Mararok commented 4 years ago

I have the same problem now :)

Mararok commented 4 years ago

@mariobittencourt I found solution, you can use 'Custom' type. I checked it with annotations

@hashKey({
    type: 'Custom',
    attributeType: 'S',
    marshall: (input) => {
      return { S: input.get() };
    },
    unmarshall: (input) => UserId.createFromSafe(input.S as string),
  })

If you are using it without annotations check it: https://github.com/awslabs/dynamodb-data-mapper-js/tree/master/packages/dynamodb-data-marshaller#custom

mariobittencourt commented 4 years ago

Thank you @Mararok. I will try to use it and see if it can work with the use cases I am considering.