TypeORM: ORMapper for TypeScript


TypeORM is a ORMapper for TypeScript.

🐞 Installation

yarn add typeorm

🐝 Basic Usage for Active Record pattern

Model Definition

Active Record pattern is an approach to access your database within your models.

import { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn() id: number;

@Column() firstName: string;

@Column() lastName: string;

@Column() isActive: boolean;

static findByName(firstName: string, lastName: string) {
return this.createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName })
.andWhere("user.lastName = :lastName", { lastName })
.getMany();
}
}

Save/Delete/Fetch

This is a example of how to use the entity:

// example how to save AR entity
const user = new User();
user.firstName = "Timber";
user.lastName = "Saw";
user.isActive = true;
await user.save();

// example how to remove AR entity
await user.remove();

// example how to load AR entities
const users = await User.find({ skip: 2, take: 5 });
const newUsers = await User.find({ isActive: true });
const timber = await User.findOne({ firstName: "Timber", lastName: "Saw" });

If you want to know more details, please see Active Record vs Data Mapper.

😸 Fetch with related table

class Review {
public static async findWithProduct(productId: number): Promise {
return await this.createQueryBuilder("review")
.leftJoinAndSelect("review.product", "product")
.where("review.product_id = :productId")
.setParameters({ productId })
.getOne();
}

@OneToOne(type => Product)
@JoinColumn({ name: "product_id" })
public product: Product;
}

🎃 Transaction

Transactions are creating using Connection:

import { getConnection } from "typeorm";

await getConnection().transaction(transactionalEntityManager => {
// do something
});

If you want to know more details, please see Transactions.

🎉 Relations

Please see the following links:

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!