NestJS Enterprise Backend APIs · Lezione

Nozioni di base sull'integrazione di TypeORM

Configuri TypeORM con NestJS, definisca le entità ed esegua operazioni di base sul database utilizzando i repository.

Lezione 3 di 311 passaggi

Nozioni di base sull'integrazione di TypeORM è una lezione NestJS Enterprise Backend APIs gratuita su CoddyKit. Questa è la lezione 3 di 3. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento NestJS Enterprise Backend APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso NestJS Enterprise Backend APIs include 3 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Intro to TypeORM in NestJS

Welcome to integrating TypeORM with NestJS! TypeORM is an Object-Relational Mapper (ORM) that helps you work with databases using TypeScript or JavaScript.

Instead of writing raw SQL queries, you interact with your database using familiar object-oriented programming concepts like classes and objects.

Why Use an ORM?

ORMs like TypeORM offer several benefits:

  • Abstraction: No need to write complex SQL.
  • Type Safety: With TypeScript, your database interactions are type-checked.
  • Portability: Easily switch between different database systems (PostgreSQL, MySQL, SQLite, etc.).
  • Productivity: Faster development with less boilerplate code.

Setting Up TypeORM Module

First, we need to install TypeORM and the database driver for your chosen database (e.g., pg for PostgreSQL, sqlite3 for SQLite).

Then, we configure the TypeOrmModule in your main application module (usually AppModule) to establish the database connection.

TypeOrmModule Configuration

Here's how you might configure TypeORM in your app.module.ts. This example uses SQLite for simplicity, which stores data in a file.

We use TypeOrmModule.forRoot() to set up the connection globally.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'db.sqlite',
      entities: [], // We'll add our entities here soon!
      synchronize: true, // Auto-create tables (dev only!)
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Defining Your First Entity

An Entity is a class that maps directly to a database table. Each instance of the entity class represents a row in that table.

We use decorators like @Entity(), @PrimaryGeneratedColumn(), and @Column() to define the table and its columns.

User Entity Example

Let's create a simple User entity. This will map to a user table in our database.

  • @PrimaryGeneratedColumn() creates an auto-incrementing primary key.
  • @Column() defines a regular column.
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

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

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column({ default: true })
  isActive: boolean;
}

Registering Entities in Module

After defining your entity, you need to tell TypeORM about it. Update your AppModule's TypeOrmModule.forRoot() configuration to include your new User entity.

This allows TypeORM to create the corresponding table in your database.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity'; // Import your entity

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'db.sqlite',
      entities: [User], // Register your User entity here
      synchronize: true,
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Introducing Repositories

TypeORM Repositories are objects that provide methods for interacting with a specific entity's table in the database.

You inject a repository into your NestJS service (e.g., UserService) to perform CRUD operations (Create, Read, Update, Delete).

Basic Operations: Create & Read

To use a repository, you inject it using @InjectRepository(). Let's see how to create a new user and retrieve all users.

  • save(): Inserts a new record or updates an existing one.
  • find(): Retrieves all records for the entity.
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  async createUser(): Promise<User> {
    const newUser = this.usersRepository.create({
      firstName: 'Coddy',
      lastName: 'Kit',
      isActive: true,
    });
    return this.usersRepository.save(newUser);
  }

  async findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }
}

TypeORM Quick Check

Which decorator is used to mark a class as an entity that maps to a database table in TypeORM?

Recap: TypeORM Basics

You've learned the basics of integrating TypeORM into your NestJS application!

  • We configured TypeOrmModule in our AppModule.
  • We defined an Entity using decorators like @Entity(), @PrimaryGeneratedColumn(), and @Column().
  • We understood how to use Repositories to perform basic database operations like creating and reading records.

Next, you'll explore more advanced CRUD operations and data handling techniques!

Gratis per iniziare

Impara TypeScript con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
20
Lezioni
76

Domande Frequenti

La lezione «Nozioni di base sull'integrazione di TypeORM» è gratuita?

Sì — il testo completo di «Nozioni di base sull'integrazione di TypeORM» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso NestJS Enterprise Backend APIs, passa a CoddyKit PRO. Il corso NestJS Enterprise Backend APIs include 3 lezioni in totale.

Cosa imparerò in «Nozioni di base sull'integrazione di TypeORM»?

Configuri TypeORM con NestJS, definisca le entità ed esegua operazioni di base sul database utilizzando i repository. Eserciti NestJS Enterprise Backend APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare NestJS Enterprise Backend APIs?

Non è richiesta alcuna esperienza precedente. NestJS Enterprise Backend APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 3.

Quanto tempo richiede la lezione «Nozioni di base sull'integrazione di TypeORM»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione NestJS Enterprise Backend APIs?

Sì. Ogni lezione NestJS Enterprise Backend APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Dependency injection spiegata
  2. DTO e pipe di validazione
  3. Nozioni di base sull'integrazione di TypeORM
← Torna a NestJS Enterprise Backend APIs