In TypeORM, you can connect to various database types and perform read/write operations across them by configuring multiple data sources. Below, I will explain how to configure and use different data sources for writing data.
Step 1: Install and Configure TypeORM
First, ensure that you have installed TypeORM and the appropriate database drivers (e.g., MySQL, PostgreSQL, etc.). For example, if you are using MySQL and PostgreSQL, you can install them using npm or yarn:
bashnpm install typeorm mysql pg
Step 2: Create Data Source Configuration
In TypeORM, you can configure multiple data sources in the ormconfig.json file. For example, the following configuration demonstrates how to set up both MySQL and PostgreSQL data sources:
json[ { "name": "mysqlConnection", "type": "mysql", "host": "localhost", "port": 3306, "username": "user", "password": "password", "database": "test", "entities": ["src/entity/**/*.ts"], "synchronize": true }, { "name": "postgresConnection", "type": "postgres", "host": "localhost", "port": 5432, "username": "user", "password": "password", "database": "test", "entities": ["src/entity/**/*.ts"], "synchronize": true } ]
In each configuration item, the name property serves as an identifier to distinguish between different data sources.
Step 3: Use Data Sources
After configuring the data sources, you can use different databases in your code by specifying the connection name. Below is an example of how to implement this in a TypeScript file:
typescriptimport { DataSource } from "typeorm"; // Create data source instances const mysqlDataSource = new DataSource({ name: "mysqlConnection", type: "mysql", // Other configurations... }); const postgresDataSource = new DataSource({ name: "postgresConnection", type: "postgres", // Other configurations... }); // Initialize connections mysqlDataSource.initialize().then(() => { console.log("Connected to MySQL"); }).catch(error => console.log("Error: ", error)); postgresDataSource.initialize().then(() => { console.log("Connected to PostgreSQL"); }).catch(error => console.log("Error: ", error)); // Use data sources for data operations async function insertData() { const mysqlEntityManager = mysqlDataSource.manager; const postgresEntityManager = postgresDataSource.manager; // MySQL database operations const newUser = mysqlEntityManager.create(User, { name: "John", age: 30 }); await mysqlEntityManager.save(newUser); // PostgreSQL database operations const newProduct = postgresEntityManager.create(Product, { title: "Book", price: 20.99 }); await postgresEntityManager.save(newProduct); }
In this example, we create two DataSource instances corresponding to MySQL and PostgreSQL databases. Using their respective EntityManager objects, we can perform CRUD operations on different databases.
Summary
By following these steps, you can flexibly handle multiple different types of databases in TypeORM. This capability enables handling various storage requirements within a single application.