Introduction
Embark on the journey of mastering NestJS, a progressive Node.js framework, by building a simple yet robust ‘Hello World’ application. This tutorial will guide you through the basics with comprehensive steps and varied complexity.
Setting Up the Environment
This section is unnecessary with almost developers but I think it can provide some useful information for beginners.
To continue, you need to have Node.js installed on your machine. Download the latest version from the official Node.js website. Once installed, you can verify its installation by running node -v
in your terminal.
Next, install NestJS CLI globally with the command npm i -g @nestjs/cli
. This command-line tool helps to initialize and develop NestJS applications efficiently.
Creating Your First NestJS App
Create your new project by executing nestjs new hello-world
. Respond to the prompts by the installer, and a new directory called ‘hello-world’ will be created with the necessary scaffolded components.
Exploring the project structure
Inspect the generated project structure, noting the src
directory which contains your application’s source code, along with entry file main.ts
. The ‘src’ folder typically houses the controllers, providers (services), modules, and other TypeScript files.
Running the application
Inside your new ‘hello-world’ directory, run the app with the command npm run start
. Once your server is up, visit http://localhost:3000
in your browser to see NestJS’s default ‘Hello World’ page.
Building a Custom ‘Hello World’
Now, let’s tailor this application to respond with a custom ‘Hello World’ message. First, we’ll need to create a controller. Generate one with the CLI tool using nest g controller hello
, which creates a ‘hello’ controller with its respective TypeScript file.
import { Controller, Get } from '@nestjs/common';
@Controller('hello')
export class HelloController {
@Get()
getHello(): string {
return 'Hello World!';
}
}
In the sourced code above, we defined a ‘hello’ route that will manage GET requests and respond with ‘Hello World!’.
Integrating a Service
Next, let’s abstract the ‘Hello World’ message to a service. Generate a new service with nest g service hello
. A service typically contains the business logic of the application.
import { Injectable } from '@nestjs/common';
@Injectable()
export class HelloService {
getHello(): string {
return 'Hello World from Service!';
}
}
Now that we’ve created our service, inject it into the HelloController:
import { Controller, Get } from '@nestjs/common';
import { HelloService } from './hello.service';
@Controller('hello')
export class HelloController {
constructor(private helloService: HelloService) {}
@Get()
getHello(): string {
return this.helloService.getHello();
}
}
With this setup, when ‘http://localhost:3000/hello’ is visited, the application will present the text: ‘Hello World from Service!’.
Add Configuration and Environment Variables
For more complex developments, managing configuration and environment variables becomes crucial. Within NestJS, this can be done using the ConfigModule
.
Add the ConfigModule to your app module as follows:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { HelloController } from './hello.controller';
import { HelloService } from './hello.service';
@Module({
imports: [ConfigModule.forRoot()],
controllers: [HelloController],
providers: [HelloService],
})
export class AppModule {}
This step allows your application to smoothly transition between development and production modes with environmental specific conditions.
Implementing Asynchronous Providers
In larger applications, services may need to handle asynchronous operations such as database queries or API requests. Here’s how to update your HelloService to simulate an async operation:
import { Injectable } from '@nestjs/common';
@Injectable()
export class HelloService {
async getHello(): Promise {
return 'Async Hello World!';
}
}
And reflect this change in the HelloController:
import { Controller, Get } from '@nestjs/common';
import { HelloService } from './hello.service';
@Controller('hello')
export class HelloController {
constructor(private readonly helloService: HelloService) {}
@Get()
async getHello(): Promise {
return await this.helloService.getHello();
}
}
This demonstrates a simple asynchronous interaction in NestJS.
Testing
Testing is critical in software development, and NestJS makes it accessible with Jest, a delightful JavaScript testing framework. Write tests for your service and controller to ensure they behave as expected.
Conclusion
This tutorial comprehensively introduces you to NestJS and drives you through creating a ‘Hello World’ application. By following these steps, you should have a good foundation on which to build more complex NestJS applications. Remember that this is just the beginning of your journey with NestJS; there is much more to explore and learn.