serverless-seoul / dynamorm

AWS DynamoDB ORM in Typescript
Apache License 2.0
55 stars 4 forks source link

Single table #8

Closed antoniopresto closed 4 years ago

antoniopresto commented 4 years ago

Hi,

Can I use this package with single table design or every entity should map to a different table?

breath103 commented 4 years ago

Since you're using typescript, there are multiple ways of doing this:

  1. Just define multiple tables with same table mapping / primaryKey, but different attribute
  @Decorator.Table({ name: `table_a`})
  class TableA {
    @Decorator.HashPrimaryKey("id")
    public static readonly primaryKey: Query.HashPrimaryKey<BlogPost, number>; 

    @Decorator.Attribute({ name: "id" })
    public id: string!;

    @Decorator.Attribute({ name: "a_attributes" })
    public a_attributes: string!;
  }

  @Decorator.Table({ name: `table_a`})
  class TableB {
    @Decorator.HashPrimaryKey("id")
    public static readonly primaryKey: Query.HashPrimaryKey<BlogPost, number>; 

    @Decorator.Attribute({ name: "id" })
    public id: string!;

    @Decorator.Attribute({ name: "b_attributes" })
    public b_attributes: string!;
  }
  1. Define single table, utilize typescript union type

    @Decorator.Table({ name: `table_a`})
    class TableAOrB {
    @Decorator.HashPrimaryKey("id")
    public static readonly primaryKey: Query.HashPrimaryKey<BlogPost, number>; 
    
    @Decorator.Attribute({ name: "id" })
    public id: string!;
    
    @Decorator.Attribute({ name: "attributes" })
    public attributes: {
      type: "A", 
      attributes: { "a": "data" }
    } | {
      type: "B", 
      attributes: { "b": "data" }
    }
    }

Theoretically using inheritance should work also, but i haven't tested or used that pattern yet so can't tell that for sure now

antoniopresto commented 4 years ago

define multiple tables with same table mapping - this should have been my question - but I think it will help someone googling :) Thank you!

breath103 commented 4 years ago

Great! since dynamorm doesn't have any centralized mapping structure such as repository, mappings are all independent entities.
even using different connection per table, or using same table but one with DAX one with ordinary connection.. all possible if you just create different class, with same mapping