TypeORM Documentation

website·Indexed 38 days ago

https://typeorm.io/

An Object-Relational Mapper (ORM) that can be used with JavaScript and TypeScript. It supports multiple databases including MySQL, MariaDB, PostgreSQL, CockroachDB, SQLite, Microsoft SQL Server, Oracle, SAP HANA, and MongoDB. The documentation covers entity definitions, the QueryBuilder, Active Record and Data Mapper patterns, migrations, and relation management.

Tokens
68.6K
Snippets
401
Records
475
Agent score
65%

What's inside TypeORM

  1. Introduction to TypeORM QueryBuilder

    The QueryBuilder is a powerful TypeORM feature that allows developers to build SQL queries using an elegant syntax, execute them, and receive automatically transformed entities. It provides a type-safe way to construct complex queries without writing raw SQL.
    const firstUser = await dataSource
        .getRepository(User)
        .createQueryBuilder("user")
        .where("user.id = :id", { id: 1 })
        .getOne()
  2. TypeORM platform compatibility overview

    TypeORM is compatible with the following platforms:

    • Node.js: Version 20+ (tested on 20 and 24).
    • Browser: Via sql.js.
    • Capacitor: Via the Capacitor driver.
    • Cordova/Ionic: Via cordova-sqlite-storage (Note: Transactions are not supported; custom webpack config required for Ionic).
    • Expo: Via Expo SQLite API.
    • NativeScript: Via nativescript-sqlite (requires Webpack).
    • React Native: Via react-native-sqlite-storage.
  3. Understand the purpose of TypeORM DataSource

    A DataSource in TypeORM manages your database connection settings and establishes the initial connection or connection pool. It is the primary entry point for interacting with the database. You must call the initialize method to establish the connection and the destroy method to close all connections in the pool. Typically, initialize is called during application bootstrap, and destroy is only called when the application is shutting down (though backend servers often keep the DataSource active for their entire lifecycle).
  4. Choose between Active Record and Data Mapper patterns in TypeORM

    TypeORM supports two architectural patterns for data persistence. The Active Record approach is recommended for smaller applications because it keeps the implementation simple. The Data Mapper approach is recommended for larger applications as it provides better maintainability and separation of concerns.
  5. Update Repository find methods for TypeORM 1.0

    Several repository methods have been removed or renamed in version 1.0:

    • findByIds is removed: use findBy with the In operator.
    • findOneById is removed: use findOneBy.
    • Repository.exist() is removed: use Repository.exists().
  6. Manage database connections with QueryRunner

    A QueryRunner instance provides a single database connection from the connection pool. It is essential to release the QueryRunner when it is no longer needed to return the connection to the pool. QueryRunner also provides its own EntityManager via the manager property, allowing multiple queries to be executed on the same connection.
    let queryRunner: QueryRunner;
    
    try {
        queryRunner = dataSource.createQueryRunner();
    
        // Use the manager to execute multiple queries on one connection
        await queryRunner.manager.update(
            Employee,
            { level: "junior" },
            { bonus: 0.2 },
        );
        await queryRunner.manager.update(
            Employee,
            { level: "senior" },
            { bonus: 0.1 },
        );
    } catch (error) {
        console.error(error);
    } finally {
        // Always release the connection
        await queryRunner.release();
    }
  7. Install and configure sql.js in TypeORM

    To use sql.js (WebAssembly SQLite), install the package and use these options:

    • database: The raw UInt8Array database to import.
    • sqlJsConfig: Initialization config for sql.js.
    • autoSave: Boolean to enable automatic persistence. Requires location or autoSaveCallback.
    • autoSaveCallback: Function called when changes are made (receives UInt8Array of the database).
    • location: File location for loading/saving the database.
    • useLocalForage: Use localforage library for async indexedDB storage in browsers.
    npm install sql.js
  8. Implement Eager Loading for relations in TypeORM

    Eager loading automatically retrieves all related data in a single query when the main entity is fetched. To enable eager loading, set { eager: true } in the relation decorator. This avoids the n+1 query problem and simplifies data access, but can result in very large queries and inefficient memory usage if too many relations are marked as eager.
    @Entity()
    export class User {
        @OneToMany(() => Post, (post) => post.user, { eager: true })
        posts: Post[]
    }
    
    // Usage
    const user = await userRepository.findOne(userId);
    // user.posts is already populated
  9. Platform requirements for TypeORM 1.0

    TypeORM 1.0 updates the minimum JavaScript target to ES2023, which requires Node.js 20 or later. Additionally, the browser Buffer polyfill has been removed; on non-Node platforms (browser, Deno, Bun), binary data is now represented as Uint8Array. Node.js users are unaffected as Buffer extends Uint8Array.
  10. Access custom request data in loggers via QueryRunner

    You can pass custom data during entity persistence or removal (e.g., via the options object in .save()). This data is accessible within the logger's methods through the queryRunner.data object, allowing you to include request-specific metadata (like URLs) in your logs.
    // 1. Pass custom data during save
    postRepository.save(post, { data: { request: request } });
    
    // 2. Access that data inside the custom logger method
    logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner) {
        const requestUrl = queryRunner && queryRunner.data["request"] ? "(" + queryRunner.data["request"].url + ") " : "";
        console.log(requestUrl + "executing query: " + query);
    }