NestJS course ยท Module 3: TypeORM and Databases

Databases and TypeORM - the imperial treasury

6 min read ยท
In this lesson12

Welcome back to the system, young legionary! Consul Caesar.js has a new challenge for you. So far you've learned to build mighty fortifications with NestJS, but every real empire needs a place to store its tributes. It's time to learn treasury management - databases!

What is a database for the empire?

Just as the Romans stored their tributes in secure vaults in the Forum Romanum, applications need somewhere to safely store their data. A database is our digital treasury that:

  • Stores tributes - application data like citizen information, orders, products
  • Protects against loss - ensures durability and integrity of data
  • Enables fast searching - like a treasury register showing exact locations
  • Controls access - only authorized legionaries can reach for tributes

Types of databases - different kinds of vaults

Relational databases (SQL)

These are like organized warehouses with precisely labeled compartments:

-- Legionaries table
CREATE TABLE legionaries (
 id SERIAL PRIMARY KEY,
 name VARCHAR(100) NOT NULL,
 cohort VARCHAR(100),
 tribute_count INTEGER DEFAULT 0
);

-- Tributes table
CREATE TABLE tributes (
 id SERIAL PRIMARY KEY,
 name VARCHAR(100) NOT NULL,
 value DECIMAL(10,2),
 legionary_id INTEGER REFERENCES legionaries(id)
);

NoSQL databases

These are like flexible bags for tributes, where you can store various things:

// MongoDB document
{
 _id: ObjectId("..."),
 name: "Marcus Aurelius",
 cohort: "Legio X Equestris",
 tributes: [
 { name: "Golden Coin", value: 100 },
 { name: "Diamond Ring", value: 500 }
 ],
 officers: {
 optio: "Gaius",
 signifer: "Marcus"
 }
}

TypeORM - the magical treasury management system

TypeORM is a powerful tool that lets us easily manage databases in TypeScript. It's like an imperial treasury management system that automatically translates our requests into a language the database understands.

Installing TypeORM in the application

npm install @nestjs/typeorm typeorm pg
npm install --save-dev @types/pg

Configuring the treasury connection

// app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
 imports: [
 TypeOrmModule.forRoot({
 type: 'postgres',
 host: 'localhost',
 port: 5432,
 username: 'consul',
 password: 'imperium123',
 database: 'roman_empire',
 entities: [__dirname + '/**/*.entity{.ts,.js}'],
 synchronize: true, // Only during development!
 }),
 ],
})
export class AppModule {}

First entity - tribute register

An entity is like a detailed register showing what a specific tribute looks like in our treasury:

// tribute.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm';

@Entity('tributes')
export class Tribute {
 @PrimaryGeneratedColumn()
 id: number;

 @Column({ length: 100 })
 name: string;

 @Column('decimal', { precision: 10, scale: 2 })
 value: number;

 @Column({ nullable: true })
 description: string;

 @Column({ default: 'unknown' })
 location: string;

 @CreateDateColumn()
 collectedAt: Date;

 @Column({ default: false })
 isCursed: boolean;
}

TypeORM decorators - instructions for the treasurer

  • @Entity() - marks this as a tribute register (table)
  • @PrimaryGeneratedColumn() - unique tribute number (primary key)
  • @Column() - description of a tribute property (column)
  • @CreateDateColumn() - automatically records the collection date
  • @UpdateDateColumn() - automatically updates the modification date

Basic operations on tributes

Creating a new tribute

// tribute.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Tribute } from './tribute.entity';

@Injectable()
export class TributeService {
 constructor(
 @InjectRepository(Tribute)
 private tributeRepository: Repository<Tribute>,
 ) {}

 async addTribute(tributeData: Partial<Tribute>): Promise<Tribute> {
 const newTribute = this.tributeRepository.create(tributeData);
 return await this.tributeRepository.save(newTribute);
 }

 async findAllTributes(): Promise<Tribute[]> {
 return await this.tributeRepository.find();
 }

 async findTributeById(id: number): Promise<Tribute> {
 return await this.tributeRepository.findOne({ where: { id } });
 }

 async updateTribute(id: number, updateData: Partial<Tribute>): Promise<Tribute> {
 await this.tributeRepository.update(id, updateData);
 return this.findTributeById(id);
 }

 async removeTribute(id: number): Promise<void> {
 await this.tributeRepository.delete(id);
 }
}

Column types - different kinds of tributes

@Entity()
export class DetailedTribute {
 @PrimaryGeneratedColumn()
 id: number;

 // Text - tribute name
 @Column('varchar', { length: 200 })
 name: string;

 // Integers - quantity
 @Column('int')
 quantity: number;

 // Decimals - value
 @Column('decimal', { precision: 10, scale: 2 })
 value: number;

 // Booleans - whether cursed
 @Column('boolean', { default: false })
 isCursed: boolean;

 // Date - when collected
 @Column('date')
 collectionDate: Date;

 // Long text - tribute history
 @Column('text')
 history: string;

 // JSON - details
 @Column('json')
 details: {
 material: string;
 origin: string;
 previousOwners: string[];
 };
}

Data validation - checking tribute quality

import { IsNotEmpty, IsPositive, IsOptional, Length } from 'class-validator';

export class CreateTributeDto {
 @IsNotEmpty({ message: 'Every tribute must have a name!' })
 @Length(3, 100, { message: 'Name must be between 3 and 100 characters' })
 name: string;

 @IsPositive({ message: 'Tribute value must be greater than zero' })
 value: number;

 @IsOptional()
 @Length(0, 500)
 description?: string;

 @IsOptional()
 location?: string;
}

Tribute module configuration

// tribute.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TributeService } from './tribute.service';
import { TributesController } from './tributes.controller';
import { Tribute } from './tribute.entity';

@Module({
 imports: [TypeOrmModule.forFeature([Tribute])],
 controllers: [TributesController],
 providers: [TributeService],
 exports: [TributeService],
})
export class TributeModule {}

Resource controller

// tributes.controller.ts
import { Controller, Get, Post, Put, Delete, Body, Param } from '@nestjs/common';
import { TributeService } from './tribute.service';
import { CreateTributeDto } from './dto/create-tribute.dto';

@Controller('tributes')
export class TributesController {
 constructor(private readonly tributeService: TributeService) {}

 @Post()
 async addTribute(@Body() createTributeDto: CreateTributeDto) {
 return await this.tributeService.addTribute(createTributeDto);
 }

 @Get()
 async getAllTributes() {
 return await this.tributeService.findAllTributes();
 }

 @Get(':id')
 async getTribute(@Param('id') id: string) {
 return await this.tributeService.findTributeById(+id);
 }

 @Put(':id')
 async updateTribute(
 @Param('id') id: string,
 @Body() updateData: Partial<CreateTributeDto>
 ) {
 return await this.tributeService.updateTribute(+id, updateData);
 }

 @Delete(':id')
 async removeTribute(@Param('id') id: string) {
 await this.tributeService.removeTribute(+id);
 return { message: 'Tribute has been removed from the treasury!' };
 }
}

Error handling - protection against curses

import { NotFoundException, BadRequestException } from '@nestjs/common';

@Injectable()
export class TributeService {
 //
 async findTributeById(id: number): Promise<Tribute> {
 if (id <= 0) {
 throw new BadRequestException('Tribute ID must be greater than zero');
 }

 const tribute = await this.tributeRepository.findOne({ where: { id } });

 if (!tribute) {
 throw new NotFoundException(`Tribute with ID ${id} was not found in the treasury`);
 }

 return tribute;
 }

 async removeTribute(id: number): Promise<void> {
 const tribute = await this.findTributeById(id);

 if (tribute.isCursed) {
 throw new BadRequestException('Cannot remove a cursed tribute!');
 }

 await this.tributeRepository.delete(id);
 }
}

Practical exercise

Now that you know the basics, it's time for your own experiments! Try creating your own entity for legionaries:

// Your code here
@Entity('legionaries')
export class Legionary {
 // Add properties:
 // - id (auto-generated)
 // - name (text, required)
 // - cohort (text, optional)
 // - tributeCount (number, default 0)
 // - joinedAt (join date)
 // - isActive (whether active, default true)
}

Summary

Congratulations! You've learned the basics of data treasury management. Now you can:

Configure TypeORM in a NestJS application Create entities - registers for your tributes Perform basic CRUD operations on data Validate data before saving to the treasury Handle errors and protect against curses

In the next lessons you'll learn advanced techniques like table relationships, migrations, and advanced queries. Consul Caesar.js is proud of your progress!

Code for this lesson: src/database-intro.ts
// Databases and TypeORM - Imperium Treasury
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

console.log("TypeORM - imperium treasury management system!");

// ===========================================
// 1. Basic entity (Entity) - tribute map
// ===========================================

@Entity('legionaries')
export class Legionary {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 100 })
  name: string;

  @Column()
  rank: string;

  @Column({ default: 0 })
  experience: number;

  @Column()
  legion: string;
}

// ===========================================
// 2. Database connection configuration
// ===========================================

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'imperium',
      password: 'roma_aeterna',
      database: 'imperium_db',
      entities: [Legionary],
      synchronize: true, // Only in development!
    }),
    TypeOrmModule.forFeature([Legionary]),
  ],
})
export class DatabaseModule {}

// ===========================================
// 3. Database types - treasury types
// ===========================================

// Relational (SQL):
// - PostgreSQL - most popular, ACID, relations
// - MySQL/MariaDB - fast, popular
// - SQLite - lightweight, file-based

// Non-relational (NoSQL):
// - MongoDB - document-based (JSON-like)
// - Redis - key-value, cache
// - Cassandra - column-based, big data

// ===========================================
// 4. ORM vs raw SQL queries
// ===========================================

// ORM (Object-Relational Mapping):
// - We write TypeScript instead of SQL
// - Automatic mapping of objects to tables
// - Type safety
// - Easier migrations

// Raw SQL:
// const result = await connection.query(
//   'SELECT * FROM legionaries WHERE rank = $1',
//   ['Centurio']
// );

// TypeORM:
// const result = await legionaryRepo.find({
//   where: { rank: 'Centurio' }
// });

console.log("\n=== SUMMARY ===");
console.log("TypeORM - ORM for TypeScript/JavaScript");
console.log("@Entity - decorator defining a table");
console.log("@Column - decorator defining a column");
console.log("@PrimaryGeneratedColumn - primary key auto-increment");
console.log("TypeOrmModule.forRoot() - connection configuration");
console.log("TypeOrmModule.forFeature() - repository registration");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is TypeORM?

  2. 2. What does the @Entity() decorator above a TypeScript class mean?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Write a Legionary entity with @Entity(), @PrimaryGeneratedColumn(), @Column() name and @Column() rank

  • Click in order

    Arrange the elements of a TypeORM entity definition in the correct order:

  • Code editor

    Write a TypeOrmModule.forRoot() configuration with type: 'postgres', host, port, username, password and database

  1. QuestionWhat is TypeORM
  2. QuestionThe @Entity decorator
  3. Coding taskFirst TypeORM entity
  4. Click in orderTypeORM entity definition
  5. QuestionTypeORM configuration in NestJS
  6. Coding taskDatabase connection configuration

Useful articles