TypeORM Installation and Project Settings


TypeORM Installation and Project Settings

TypeORM is a powerful ORM (Object Relational Mapping) library that is popularly used in Node.js and TypeScript-based projects. TypeORM, which simplifies database operations especially in large-scale applications, offers flexible solutions in terms of installation and project settings. In this article, TypeORM installation will be explained step by step and how to configure basic project settings will be demonstrated with examples.

How to Install TypeORM?

For a successful TypeORM installation, you first need to initialize a Node.js project. Then, TypeORM is added along with the relevant database packages as needed. Below is an example installation for PostgreSQL. However, different databases such as MySQL, MariaDB, SQLite, and MongoDB are also supported.

npm init -y
npm install typeorm reflect-metadata pg

The typeorm and reflect-metadata packages must be installed. The pg package is required for PostgreSQL support. Depending on the database you use, different drivers such as mysql, mariadb, or sqlite3 can be installed.

Configuring TypeORM Project Settings

After the installation, a ormconfig.json file is created in the project's root directory to define basic database connection settings. Below, an example configuration is provided using the modern method data-source.ts. With the new versions of TypeORM, this file type is the recommended way of configuration.

import "reflect-metadata";
import { DataSource } from "typeorm";

export const AppDataSource = new DataSource({
  type: "postgres",
  host: "localhost",
  port: 5432,
  username: "postgres",
  password: "password",
  database: "testdb",
  synchronize: true,
  logging: false,
  entities: [__dirname + "/entity/*.{js,ts}"],
  migrations: [],
  subscribers: [],
});

In this file, database connection settings are clearly shown. The synchronize property makes development easier but it is recommended to set it as false in the production environment. The entities array specifies which files the ORM will watch.

First Connection Test with TypeORM

After all connection settings are made, you can write a short test code to check if the ORM is working correctly:

import { AppDataSource } from "./data-source";

AppDataSource.initialize()
  .then(() => {
    console.log("Successfully connected to the database!");
  })
  .catch((error) => console.error("Connection error:", error));

Conclusion

TypeORM installation and project settings add professionalism to the development process and make your code sustainable. By following the steps in this article, you can quickly start your projects with TypeORM and take advantage of the modern Node.js ecosystem. By following TypeORM's advanced documentation, it is possible to develop much more complex and customizable projects.