@nestjs/typeorm Documentation

repository·master·Indexed 24 days ago

https://github.com/nestjs/typeorm

Official NestJS integration for TypeORM, providing a dedicated module to use the TypeORM Object-Relational Mapper within the NestJS dependency injection system. Includes the TypeOrmModule for global and feature-based configuration, decorators like @InjectRepository(), @InjectDataSource(), and @InjectEntityManager(), and utility functions for generating injection tokens. Supports multiple data sources, async configuration via TypeOrmModuleAsyncOptions, and provides compatibility wrappers for TypeORM versions.

Tokens
3K
Snippets
2
Records
29
Agent score
79%

What's inside @nestjs/typeorm

  1. Define an entity using a class or an EntitySchema

    master
    When configuring TypeORM entities in NestJS, you can provide either a class decorated with @Entity() or a TypeORM EntitySchema object. The EntityClassOrSchema type represents this union, allowing for both the decorator-based approach (standard for TypeScript classes) and the schema-based approach (useful for cases where you cannot or do not want to use decorators on the class itself).
  2. Compatibility for TypeORM Connection and AbstractRepository

    master

    The @nestjs/typeorm package provides compatibility exports for Connection and AbstractRepository. These symbols were removed in TypeORM v1.0.0 (replaced by DataSource in TypeORM 0.3.0+).

    If you are using TypeORM v1.0.0 or newer, these exports will resolve to undefined. If you are using TypeORM 0.3.x or older, they will resolve to the original TypeORM classes. This allows @nestjs/typeorm to remain compatible across different major versions of TypeORM without causing runtime crashes or TypeScript errors when skipLibCheck is disabled.

  3. Configure the PostgreSQL service via docker-compose.yml

    master

    The project provides a docker-compose.yml file to spin up a PostgreSQL database instance for testing or local development. The service is named postgres and uses the postgres:18.4 image.

    By default, the configuration sets the following environment variables and port mappings:

    • POSTGRES_USER: root
    • POSTGRES_PASSWORD: root
    • POSTGRES_DB: test
    • Host Port: 3306 (mapped to container port 5432)

    Note: The host port is mapped to 3306, which is unconventional for PostgreSQL (typically 5432) and may conflict if you have MySQL running on your host.

    version: "3"
    
    services:
      postgres:
        image: postgres:18.4
        environment:
          POSTGRES_USER: root
          POSTGRES_PASSWORD: root
          POSTGRES_DB: test
        ports:
          - "3306:5432"
        restart: always
  4. Resolve CircularDependencyException

    master

    The CircularDependencyException is thrown when the TypeORM module detects a circular dependency in your entity relationships or module imports.

    To resolve this, follow these steps:

    1. Use forwardRef(): Ensure that both sides of a bidirectional relationship are decorated with forwardRef() to allow NestJS to resolve the dependency.
    2. Avoid Barrel Files: Minimize the use of barrel files (index.ts files that re-export multiple entities or modules), as they can cause unexpected circular dependency behavior during module resolution.
  5. Resolve DuplicateDataSourceException

    master

    The DuplicateDataSourceException is thrown when multiple TypeORM data sources are registered with the same name. In NestJS, if you register more than one data source using TypeOrmModule.forRoot() or TypeOrmModule.forRootAsync(), each must have a unique name property to prevent them from overriding each other.

    If the error message mentions default (unnamed), it means you have multiple registrations that did not specify a name property, causing them all to attempt to use the default name.

  6. Get the injection token for a Repository

    master

    Use getRepositoryToken() to generate the unique injection token for an Entity or a Repository. This is useful when you need to manually resolve a repository from the NestJS dependency injection container, especially when working with multiple data sources.

    • If the entity is a standard Entity class, it returns a string token like EntityNameRepository.
    • If the entity is an EntitySchema, it uses the schema's name.
    • If a custom dataSource name is provided, the token is prefixed with that name followed by an underscore (e.g., connectionName_EntityNameRepository).
    • If the entity is already a Repository class (custom repository), it uses getCustomRepositoryToken() to generate the token.
  7. Use TypeOrmModule to integrate TypeORM with NestJS

    master
    The @nestjs/typeorm package provides the TypeOrmModule class, which is the primary entry point for configuring and integrating TypeORM into a NestJS application. You typically use TypeOrmModule.forRoot() to establish a global connection to your database and TypeOrmModule.forFeature() to register specific entities within a module.
  8. Import TypeORM options interfaces

    master
    The lib/interfaces/index.ts file serves as the entrypoint for all TypeORM-related interfaces in this package. You can import configuration and option interfaces from this entrypoint to ensure type safety when configuring your NestJS TypeORM integration.
  9. Configure the TypeORM module using TypeOrmModule.forRoot()

    master
    Use TypeOrmModule.forRoot() to register the TypeORM module with your database connection options. This method initializes the core TypeORM module. You can optionally provide a name as a second argument to override options.name, allowing you to configure the data source name separately from the connection options.
  10. Get the injection token for a DataSource

    master

    Use getDataSourceToken() to retrieve the injection token for a TypeORM DataSource.

    • If you pass the string 'default', it returns the DataSource class itself.
    • If you pass a custom string name, it returns a string token formatted as ${name}DataSource.
    • If you pass a DataSource or DataSourceOptions object, it extracts the name and returns the corresponding token.

    Note: getConnectionToken is a deprecated alias for getDataSourceToken.