Separating Entity Definition
Defining Schemas
You can define an entity and its columns right in the model, using decorators. But some people prefer to define an entity and its columns inside separate files which are called "entity schemas" in TypeORM.
Simple definition example:
import { EntitySchema } from "typeorm"
export const CategoryEntity = new EntitySchema({
name: "category",
columns: {
id: {
type: Number,
primary: true,
generated: true,
},
name: {
type: String,
},
},
})Example with relations:
Complex example:
If you want to make your entity typesafe, you can define a model and specify it in schema definition:
Extending Schemas
When using the Decorator approach it is easy to extend basic columns to an abstract class and simply extend this.
For example, your id, createdAt and updatedAt columns may be defined in such a BaseEntity. For more details, see
the documentation on concrete table inheritance.
When using the EntitySchema approach, this is not possible. However, you can use the Spread Operator (...) to your
advantage.
Reconsider the Category example from above. You may want to extract basic column descriptions and reuse it across
your other schemas. This may be done in the following way:
Now you can use the BaseColumnSchemaPart in your other schema models, like this:
You can use embedded entities in schema models, like this:
Be sure to add the extended columns also to the Category interface (e.g., via export interface Category extend BaseEntity).
Single Table Inheritance
In order to use Single Table Inheritance:
Add the
inheritanceoption to the parent class schema, specifying the inheritance pattern ("STI") and thediscriminator column, which will store the name of the child class on each rowSet the
type: "entity-child"option for all children classes' schemas, while extending the parent class columns using the spread operator syntax described above
Using Schemas to Query / Insert Data
Of course, you can use the defined schemas in your repositories or entity manager as you would use the decorators.
Consider the previously defined Category example (with its Interface and CategoryEntity schema) in order to get
some data or manipulate the database.
Last updated
Was this helpful?