In this post, we’ll be introducing Nest.js for Angular developers. Nest.js is particularly interesting for them since it was heavily inspired by Angular and built for TypeScript. So what’s Nest.js?
Nest.js is an open source MIT-licensed progressive Node framework, written in TypeScript and sharing many concepts with Angular. It’s for the server side and can be used to build efficient, reliable and scalable web applications for the enterprise. It’s built by Kamil Mysliwiec.
Nest.js combines the best concepts of Object Oriented Programming, Functional Programming and Functional Reactive Programming.
Nest.js has a plethora of features such as:
Since it makes use of TypeScript and the base concepts of Angular, Angular developers can learn it quickly and will be able to create backends for their Angular apps without resorting to other server-side frameworks.
Behind the curtains, Nest.js makes use of the existing and mature libraries that Node.js developers have used for a long time, such as Express.js and TypeORM.
Express is a fast, unopinionated, minimalist web framework for Node.js that provides many HTTP utilities for easily and quickly building robust REST APIs. For TypeORM, it’s the most mature ORM (Object Relational Mapper) for TypeScript language and modern JavaScript. It has support for both Active Record and Data Mapper patterns, which allow you to build high quality, loosely coupled, scalable and maintainable applications on top of the most popular existing database systems like MySQL, PostgreSQL and Oracle.
To get started with Nest.js, you need a few prerequisites. Since this introductory tutorial assumes you are an Angular developer, you may already have them all:
Nest CLI is a command-line interface utility that allows you to quickly generate projects with the base files and necessary dependencies. It also allows you to scaffold various artifacts like components and modules, serving the application in development and building the final production-ready application. The Nest CLI is based on the Angular Devkit package and uses nodemon to watch file changes.
Let’s get started by installing Nest CLI. Open a new terminal and run the following command:
npm install -g @nestjs/cli
Please note that you may need to add sudo before your command in Debian-based systems or macOS, or use an administrator CMD prompt in Windows. If you want to install packages globally on your system without being a superuser you need to fix your npm permissions.
After installing the CLI, you can use it to quickly generate Nest.js projects and work with them.
After installing the CLI, let’s generate a first project. Head back to your terminal and run the following command:
nest new firstnestproject
The CLI will ask you for some information about your project such as the description, version and author. You can submit these details or just leave them empty and hit Enter.
The CLI will create a bunch of files and folders then prompt you for the package manager you want to use with your project. You can choose either npm or yarn, but we’ll proceed with npm for the purposes of this tutorial.
After successfully installing the required dependencies, you can navigate to your project’s root folder and run the following command to start a live-reload development server based on nodemon:
npm run start:dev
You can use your web browser to navigate to http://127.0.0.1:3000/
, where your Nest server is listening. You should be able to see a page with Hello World!.
You can leave this server running and start a new terminal for the other commands we’ll be running in this tutorial.
The Nest.js project we generated has a predefined structure with best practices for testability, scalability, and maintainability. Let’s take a look in more detail.
This is a screenshot of the project structure:
The project has a node_modules
folder and a package.json
file which are necessary for every Node.js project. It also has:
<a href="https://www.typescriptlang.org/docs/handbook/tsconfig-json.html" target="_blank">tsconfig.json</a>
file for configuring TypeScriptnodemon.json
file for nodemon configurationtslint.json
file for TypeScript lintingnest-cli.json
for CLI configurationsrc/
folder containing the actual code of the projecttest/
folder containing the tests.Nest.js projects have a modular architecture. This is the definition of modular programming from Wikipedia:
Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.
In Nest.js, you can create a module as a TypeScript class annotated with the@Module()
decorator, which provides the metadata that will be used to organize the application structure.
This is an image from the official Nest.js website of how modules can be structured in an example application:
Each Nest.js application has at least one module, called the root module.
You can create modules using the CLI with thenest generate module
command. Let’s create a module in our project. Head back to your terminal, make sure you are navigated to the project’s root folder and run the following command:
nest generate module example
This will generate the src/example/example.module.ts
file and will update the src/app.module.ts
file to include the newly created module.
If we open the module file we’ll get the following content for a basic Nest module:
import { Module } from '@nestjs/common';
@Module({})
export class ExampleModule {}
This is a simple TypeScript class decorated with the @Module()
decorator available from the @nestjs/common
package.
Now, if you open the main application module in src/app.module.ts
file, you should see the module imported:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ExampleModule } from './example/example.module';
@Module({
imports: [ExampleModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
ExampleModule
is imported from the ./example/example.module
path and added to the imports
array.
In Nest.js, controllers are used to handle incoming HTTP requests and return responses. They are mapped to routes.
You can create a controller by defining a TypeScript class and using the @Controller()
decorator.
In your terminal, run the following command to generate a controller:
nest generate controller example/example
We created a controller named example
and we prefixed the name with the example/
path, which instructs the CLI to make this controller part of the example
module we created before.
Open the src/example/example/example.controller.ts
file, you should see the following code:
import { Controller } from '@nestjs/common';
@Controller('example')
export class ExampleController {}
If you open the src/example/example.module.ts
file, you’ll see the controller imported and included in the imports
array of the example
module:
import { Module } from '@nestjs/common';
import { ExampleController } from './example/example.controller';
@Module({
imports: [ExampleModule],
controllers: [ExampleController]
})
export class ExampleModule {}
Let’s go back to our example
controller and create some routes. Re-open the src/example/example/example.controller.ts
file and add the following imports:
import { Get, Post, Body } from '@nestjs/common';
Next, add an index()
method:
@Get()
index() {
return "Example Controller!";
}
We decorate the method with the @Get()
decorator to create a route that accepts GET requests and return a response with the Example Controller! text. We can access this route from the 127.0.0.1:3000/example
URL. You should see a blank page with Example Controller! text.
Next, let’s add a route that accepts POST requests. Add the following method:
@Post('echo')
echo(@Body() data): any {
return data;
}
We create an example/echo
route that will receive a JSON object and return it back. We use the @Body()
decorator to extract the body from the response. Using a REST API client (cURL or Postman etc.), you can send a POST request with some data to the 127.0.0.1:3000/example/echo
URL and get the data back. Here is an example:
In this article, we’ve introduced the Nest.js framework for Angular developers. We have also seen how to install the Nest CLI and used it to create an example project and various artifacts like modules and controllers. For more in-depth details about the other concepts, you can read the official docs.
Thanks for reading ❤
#angular #web-development