TypeORM is an ORM (Object-relational mapping) that can be used with TypeScript and JavaScript. It's used for developing applications that use databases.
We set up TypeORM, first, by creating a model. It tells TypeORM to create a database table. Each of your models in your application is a database table. A model is basically a class that has fields in it. In order for the database table to be created, we need to put the decorator, "@Entity()" above the class declaration. Here is an example from the official document:
import { Entity } from "typeorm"
@Entity()
export class Photo {
id: number
name: string
description: string
filename: string
views: number
isPublished: boolean
}
We know that each column in a table is labeled, and in our case, we want those labels to be "id", "name", "description", "filename", "views", and "isPublished," which are our fields in the class Photo (see above). In order to make each of those a column in our table, we want to put the decorator, "@Column()" above each of them.
We need at lease one primary key column for each entity. For this, you can use the decorator, "@PrimaryColumn()" (instead of @Column()) or "@PrimaryGeneratedColumn()," if you'd like to auto-generate the id.
You can create relationships (i.e. one-to-one, one-to-many, many-to-one, and many-to-many) with other classes by using the "@JoinColumn()" decorator. If you're creating an one-to-one relationship for the class PhotoMetadata and the class Photo, from the class PhotoMetadata, you will have something that looks like this:
@OneToOne(() => Photo)
@JoinColumn()
photo: Photo
However, this is not enough. You should add an inverse relation like this:
@OneToOne(() => Photo, (photo) => photo.metadata)
@JoinColumn()
photo: Relation<Photo>
And in the class Photo, you also need to do a similar thing:
@OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
metadata: Relation<PhotoMetadata>
Notice that we do not have the "@joinColumn()" decorator for this one; it's because we only need to (should) use the decorator for one side, not both! Also, all these decorators need to be imported from 'typeorm' in each class/entity file.