Skip to content

Entities

Anshuman Chhapolia edited this page Mar 23, 2024 · 2 revisions

Entities

Entities are the classes that represent the tables in the database. They are the classes that are used to interact with the database.

We use typeorm to define our entities. Read more about typeorm entities here

@smoke-trees/postgres-backend exposes a BaseEntity class that you must extend to get the prebuilt features like id, createdAt, updatedAt etc. id is an abstract property for you to decide the type of the primary key.

Here is an example of how to declare an entity:

@Entity({ name: "address_demo" })
@Documentation.addSchema({ type: "object" })
export class Address extends BaseEntity {
  @PrimaryGeneratedColumn("increment", { name: "id" })
  @Documentation.addField({ type: "number" })
  id!: number;

  @Column({ name: "line1", type: "varchar" })
  @Documentation.addField({ type: "string" })
  line1!: string;

  @Column({ name: "line2", type: "varchar" })
  @Documentation.addField({ type: "string" })
  line2!: string;

  @Column({ name: "city", type: "varchar" })
  @Documentation.addField({ type: "string" })
  city!: string;

  @Column({ name: "state", type: "varchar" })
  @Documentation.addField({ type: "string" })
  state!: string;
}

As you can see we use snake case for table and column names as they make querying easier when you are using a database that is case insensitive like postgres.

The @Documentation.addSchema and @Documentation.addField decorators are used to generate the swagger documentation for the entity. Read more about documentation here.

As a naming scheme in smoketrees we use Entity class name to name the file. So the above example will be in a file named Address.entity.ts.

Clone this wiki locally