Serializer / Deserializer

Serializer

You can resolve value of dynamoProperty using by sourceObject. For example, alias : id is resolved to [x, y].join("_") It is good for generate composite key.

@DynamoEntity()
class Entity {
    @DynamoProperty({
        keyType: KeyType.hash,
        propertyName: "id",
        serializer: (arg: SerializerArg<Entity>) => {  // <<<
            const source: Entity = arg.source;
            return [source.x, source.y].join("_");
        }
    })
    __id?: string;

    x: string;
    y: string;

    constructor(x: string, y: string) {
        this.x = x;
        this.y = y;
    }
}
const entity = new Entity("Hello", "World!");
const dynamo = Mapper.formation(entity, Entity);

It will be formationed as,

{
    "id": {
        "S": "Hello_World!"
    }
}

Deserailizer

Also you can revert using by value of DynamoItem. The deserializer returns fragment to return to the original object. You can have only one Serializer and only one Deserializer in each Property. All fragments are merged.

@DynamoEntity()
class Entity {
    @DynamoProperty({
        keyType: KeyType.hash,
        propertyName: "id",
        serializer: (arg: SerializerArg<Entity>) => {
            const source: Entity = arg.source;
            return [source.x, source.y].join("_");
        },
        deserializer: (arg: DeserializerArg): Partial<Entity> => { // <<<
          const token: string[] = arg.dynamo.id.S!!.split("_");
          return {
              x: token[0],
              y: token[1]
          };
      }
    })
    __id?: string;

    x: string;
    y: string;

    constructor(x: string, y: string) {
        this.x = x;
        this.y = y;
    }
}

Last updated

Was this helpful?