How to use SQL databases in a NestJS application with TypeORM

An ORM (Object-Relational Mapper) is a library that implements the object-relational mapping technique. This allows you to write SQL database queries using the object-oriented paradigm of your preferred language.

TypeORM is a TypeScript ORM that makes interfacing with various databases easy. It works with SQL databases but also interfaces well with NoSQL databases like MongoDB.

NestJS provides high level support for TypeORM out of the box. The dedicated TypeORM package makes integration relatively easy.

Step 1: Install dependencies

Before using TypeORM in a NestJS application, you must install it with its native NestJS package and your preferred SQL database. SQLite is a simple, no-installation option.

Run the following command to install TypeORM and its native NestJS package, using the npm package manager:

npm install @nestjs/typeorm typeorm

Run the following command to install SQLite:

npm install sqlite3

Step 2: Create an entity

An entity is a set of fields defining the data stored in a database. TypeORM uses the entity file to create a table in your database.

Follow the steps below to create an entity:

  1. Create a file in your app module and name it following the NestJS naming convention (.entity.ts).
  2. In your entity file, import the Entity, Columnand PrimaryGeneratedColumnPrimaryGeneratedColumnPrimaryGeneratedColumn decorators type shape.
  3. In your entity file, create and export a class.
  4. Populate the class with the values ​​you want in your database, like identifier, Last nameetc
  5. Annotate your entity class with the entity decorator. This makes your class recognizable to TypeORM as an entity.
  6. Annotate your id property with the PrimaryGeneratedColumn decorator. This tells TypeORM to mark the identifier as the primary key and increments it automatically.
  7. Annotate the remaining properties with the Column decorator. This adds them as columns in your database.

For instance:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

export class Test {
id: number;

property_1: string;

property_2: string;

property_3: string;

The entity file above creates this table in your database:

identifier integer(11) PRIMARY KEY AUTO_INCREMENT
property_1 varchar(255)
property_2 varchar(255)
property_3 varchar(255)

The TypeORM Documentation covers entities in more detail.

Step 3: Connect your app to a database

Now that your entity is configured, you need to connect your application to a database. This example uses SQLite.

Follow the steps below to connect your application to a database:

  1. In the root module of your applications (usually the app.module.ts file), import TypeOrmModule of @nestjs/typeorm.
  2. In the same file, import all your entities.
  3. In the imports table, call it forRoot method on TypeOrmModule. The forRoot method shares the database connection through all modules of your application.
  4. Pass an empty object as an argument in the forRoot method; this will be the TypeORM configuration object.
  5. Add a property, typeto the configuration object and set it to “sqlite”. The type property indicates the name of the database you are using.
  6. Add another property, databaseto the configuration object and set it to “test.db”. The database property indicates your preferred name for your database.
  7. Add another property, entities, to the configuration object and set it to an empty array. Fill the empty array with the entities you imported earlier.
  8. Add another property, to sychronizeand fix it true; this property synchronizes your entities with your database and updates it every time you run the code. You should only set this property to true in development. During production, you must set it to fake to avoid data loss.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Test } from './test/test.entity';
import { Entity2 } from './entity/entity.entity';
import { TestModule } from './test/test.module';

imports: [
type: 'sqlite',
database: 'test.db',
entities: [Test, Entity2],
synchronize: true,
controllers: [],
providers: [],
export class AppModule {}

Step 4: Creating a Repository

A repository is an entity’s access layer for performing queries (insert, delete, save, search, etc.) on a table created by the entity in the database. TypeORM supports the repository design pattern, so each entity has its own repository.

TypeORM automatically creates a repository for your entity when you follow the steps below:

  1. In your entity’s module file, import TypeOrmModule of @nestjs/typeorm and import your entity.
  2. Created a imports table in the @Module decorator.
  3. In the imports array, call the for Feature method on TypeOrmModule.
  4. Pass an array as an argument in your and fill the array with your entity.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TestController } from './test.controller';
import { TestService } from './test.service';
import { Test } from './test.entity';

imports: [TypeOrmModule.forFeature([Test])],
providers: [TestService],
controllers: [TestController],

Step 5: Injecting your repository into its service using dependency injection

Dependency injection is a software engineering technique that is a form of the principle of inversion of control. It shifts the burden of managing dependencies from client code to the library or service it depends on.

Follow the steps below to inject your deposit into a service:

  1. In your service file, import Deposit of type shape and the InjectRepository decorator of @nestjs/typeorm. Also import the entity you want to inject into its repository.
  2. In your service class, create a builder.
  3. Declare a private variable, depositas a parameter in the constructor to initialize it.
  4. Assign a repository type to the repository with a generic type of your entity.
  5. Annotate the repository with the InjectRepository decorator and pass your entity as an argument.

import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Test } from './test.entity';

export class TestService {
private repo: Repository<Test>,
) {}

Now that your configuration is complete, you can perform SQL queries on it to retrieve or modify data.

Make SQL queries with TypeORM

You can perform any simple SQL query by calling TypeORM’s repository methods on the deposit variable inside your class of service. You can also create complex SQL queries using TypeORM’s query builder.

Source link

Comments are closed.