Daniel Ferber
Daniel Ferber

Reputation: 311

On TypeORM, I am required to specify all relevant ColumnOptions?

I am working on a scenario were database model is maintained by another team.

When describing the Entity on TypeORM for the application, do I need to repeat the database description within the @Column annotation?

For example, if a column is nullable on the database, do I need to specify @Column({ nullable: true }) on the @Entity? Does TypeORM infer missing ColumnOptions attributes from the database model?

I am concerned about 'repeating myself' when coding the entities. And that database model may diverge from the TypeORM model.

I understand that ColumnOptions are intended for generating automatically the datamodel/migration ddl script.

Upvotes: 2

Views: 968

Answers (1)

csakbalint
csakbalint

Reputation: 786

If you follow the basic model of how TypeORM defines database entities, then you must annotate every property in the class you want to be a column in the database.

For example, if a column is nullable on the database, do I need to specify @Column({ nullable: true }) on the @Entity?

Do not forget, that typescript classes contains type declarations, which disappear when you compile them to js. There will be no property definitions in the end, so typescript wouldn't know if a column must be nullable.

Does TypeORM infer missing ColumnOptions attributes from the database model?

Note, that usually databases have different (or often more) data types than we can describe in typescript (or javascript). Let's take an example with PostgreSQL: we can define dates multiple ways in the database, but none of them resembles to the typescript (or javascript) counterpart: the Date object.

TypeORM can make guesses from property types (by using the reflect-metadata library), but annotating everything would be the best practice, because in that way, you'll get everything exactly, how you want.

I am concerned about 'repeating myself' when coding the entities. And that database model may diverge from the TypeORM model.

That is a valid concern in this case, and fortunately TypeORM has a solution for separating types and model definitions. You can read more about it here.

I hope it could help!

Upvotes: 2

Related Questions