Implementation And Advancements In NestJS

Introduction

This would be a series of articles, in this article, we would talk about the implementation of new custom APIs and connect with the PostgreSQL database in the existing NestJS project

It will cover the following things,

  • What is NestJS? (covered in the first article)
  • Background (covered in the first article)
  • Installation (covered in the first article)
  • Hands-on Lab – Create a sample NestJS project (covered in the first article)
  • In-depth Explanation - Out-of-the-box files(covered in the second article)
  • Hands-on Lab – Create custom APIs and connect with the PostgreSQL database in the existing NestJS project (current article)

Hands-on Lab – Create custom API and connect with the PostgreSQLdatabase in the existing NestJS project

  • Open Visual Code and let’s try to create a GET API to return all the tags mentioned in any job site.
  • Create a new folder as a tag under the src folder
  • Install PostgreSQL using the following link - https://www.postgresql.org/download/windows/
  • Create a table in PostgreSQL with the database name as sampletest, table as tags, and, a couple of entries there with id and name fields

Create a config file for PostgreSQL named ormconfig.ts and see the code below,

import { PostgresConnectionOptions } from "typeorm/driver/postgres/PostgresConnectionOptions";
const config: PostgresConnectionOptions = {
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    username: 'postgres',
    password: 'gourav30',
    database: 'sampletest',
    entities: [__dirname + '/**/*.entity{.ts,.js}'],
    synchronize: true
}
export default config;

Create an entity named tag.entity.ts and see the code below,

import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity({name:'tags'})
export class TagEntity{
    @PrimaryGeneratedColumn()
    id:number;
    @Column()
    name:string;
}

Create a module named tag.module.ts and see the code below,

import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { TagController } from "./tag.controller";
import { TagEntity } from "./tag.entity";
import { TagService } from "./tag.service";
@Module({
    imports:[TypeOrmModule.forFeature([TagEntity])],
    controllers:[TagController],
    providers:[TagService]
})
export class TagModule{
}

Create a controller named tag.controller.ts and see the code below,

import { Controller, Get } from "@nestjs/common";
import { TagEntity } from "./tag.entity";
import { TagModule } from "./tag.module";
import { TagService } from "./tag.service";

@Controller('tags')
export class TagController {
    constructor(private readonly tagService: TagService) { }
    @Get()
    async findAll(): Promise<{ tags: string[] }> {
        const tags = await this.tagService.findAll();
        return {
            tags: tags.map(tag => tag.name),
        }
    }
}

Create a service named tag.service.ts and see the code below,

import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { TagEntity } from "./tag.entity";
@Injectable()
export class TagService {
    constructor(@InjectRepository(TagEntity)
    private readonly tagRepository: Repository<TagEntity>) { }
    async findAll(): Promise<TagEntity[]> {
        return await this.tagRepository.find();
    }
}

Changes in the app.module.ts and see the code below,

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import ormconfig from './tag/ormconfig';
import { TagModule } from './tag/tag.module';

@Module({
  imports: [TypeOrmModule.forRoot(ormconfig), TagModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }
  • Also, below are the packages that need to be installed explicitly
    • typeorm
    • pg
  • Once, this is done, run the application by executing the below command and look at the browser with the output.

Implementation and advancements in NestJS

In this article, we talked about the implementation of a new custom GET API, connecting with the PostgreSQL database.

Stay tuned for the next series of articles on different topics, hope you see you guys again soon.

Happy learning!


Similar Articles