DEV Community

Dwi purnomo
Dwi purnomo

Posted on • Updated on

TypeORM Connection in NestJS

Post in Indonesian, TypeORM Connection in NestJS.

A software can have a function to save data to database. To save data, usually it uses software such as MySQL, SQLite, or MongoDB with communication using ORM (Object-relational Mapping).

NestJS has three ORM support namely TypeORM, Sequelize and Mongoose. In this tutorial I will only use TypeORM. The advantages of TypeORM in NestJS over other ORMs are that TypeORM and Nest Framework are both built using Typescript language so that they can be well integrated.

Following are the steps to connect a MySQL database to a Nest Framework application using TypeORM:

Install the dependencies.

To begin, we will install the TypeORM dependencies. We will use MySQL as the database.

$ npm install --save @nestjs/typeorm typeorm mysql

Create a database in MySQL.

We will create a database now that will be connected to our Nest application in MySQL.

CREATE DATABASE hello;

Make a Connection Configuration.

Now, we will make a connection configuration in AppModule to connect to our MySQL hello database. Import and use the TypeOrmModule from Nest here.

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

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'hello',
      entities: [__dirname + '/**/*.entity{.ts,.js}']
    }),
  ],
})
export class AppModule {}

Done, our application can be connected to our hello database now. The username and password configuration can be different, adjust it to fit yours.

Additional: TypeORM CLI.

TypeORM has CLI capabilities that can be used to create entities, migrations, etc. If we make a connection configuration like no. 3 above, we cannot use TypeORM's CLI.

As an alternative, we can make a json-based configuration.

Create a file called ormconfig.json at the root of this project, fill in the configuration with:

{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "root",
  "password": "root",
  "database": "hello",
  "entities": ["src/**/*.entity{.ts,.js}"],
}

Once again, The username and password configuration can be different, adjust it to fit yours.

Now, delete the connection configuration inside TypeOrmModule.forRoot() and make it only calls the TypeOrmModule.forRoot()

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

@Module({
  imports: [TypeOrmModule.forRoot()],
})
export class AppModule {}

Done, now we can use the TypeORM CLI because our application now read the connection configuration from ormconfig.json.

Top comments (0)