Getting Started with TypeORM

Installation

To begin using TypeORM, you'll need to install it along with the necessary database driver. For this example, we will use PostgreSQL. Run the following command to install TypeORM and the PostgreSQL driver:

npm install typeorm reflect-metadata pg

Setting Up the Connection

Create a new file named ormconfig.json in your project root to configure your database connection:

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "your_username",
  "password": "your_password",
  "database": "your_database",
  "synchronize": true,
  "logging": false,
  "entities": [
    "src/entity/**/*.ts"
  ]
}

Creating Entities

Entities in TypeORM represent database tables. Let's create a simple User entity. Create a directory named entity and add a file named User.ts:

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

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

    @Column()
    name: string;

    @Column()
    email: string;

    @Column()
    age: number;
}

Initializing the Connection and Using the Repository

In your main application file (e.g., index.ts), initialize the TypeORM connection and use the repository pattern to interact with the database:

import "reflect-metadata";
import { createConnection } from "typeorm";
import { User } from "./entity/User";

createConnection().then(async connection => {
    const userRepository = connection.getRepository(User);

    // Create a new user
    const newUser = userRepository.create({
        name: "John Doe",
        email: "[email protected]",
        age: 30
    });
    await userRepository.save(newUser);
    console.log("User has been saved: ", newUser);

    // Fetch all users
    const users = await userRepository.find();
    console.log("All users: ", users);
}).catch(error => console.log(error));

Performing CRUD Operations

TypeORM makes it easy to perform CRUD (Create, Read, Update, Delete) operations. Here’s how you can implement these operations:

Create

const user = userRepository.create({
    name: "Jane Doe",
    email: "[email protected]",
    age: 25
});
await userRepository.save(user);

Read

To read users, you can use various methods:

// Find one user by ID
const user = await userRepository.findOne(1);

// Find all users
const allUsers = await userRepository.find();

Update

To update a user, retrieve it first, modify the properties, and then save:

const userToUpdate = await userRepository.findOne(1);
if (userToUpdate) {
    userToUpdate.age = 31;
    await userRepository.save(userToUpdate);
}

Delete

To delete a user, you can use the remove method:

const userToDelete = await userRepository.findOne(1);
if (userToDelete) {
    await userRepository.remove(userToDelete);
}

Advanced Features

TypeORM also supports advanced features such as:

  • Relations: Define relationships between entities using decorators like @OneToMany, @ManyToOne, etc.
  • Query Builder: For complex queries, you can use TypeORM's query builder for more control:
const users = await userRepository
    .createQueryBuilder("user")
    .where("user.age > :age", { age: 20 })
    .getMany();

Best Practices

  1. Use Migrations: Always use migrations for database schema changes to keep track of changes and ensure consistency across environments.
  2. Enable Synchronization in Development Only: Set synchronize to false in production to avoid unintentional data loss.
  3. Leverage TypeScript Types: Define types for your entities and use TypeScript features to ensure type safety throughout your application.

Conclusion

TypeORM is a robust library that simplifies SQL database management in TypeScript applications. With its powerful features and ease of use, developers can efficiently perform database operations while maintaining type safety. By following the best practices outlined in this tutorial, you can create scalable and maintainable applications.


Learn more with useful resources