Getting Started with NestJS

How to build web services with TypeScript & NestJS

Kenneth Reilly
ITNEXT

--

The NestJS Logo — https://nestjs.com

Introduction

Developers today have many options available when it comes to building web services and other server-side applications. Node has become a popular choice, however many programmers prefer a more robust language than JavaScript, especially those coming from modern OOP languages like C#, C++, or Java (to name just a few). While TypeScript lends itself well to Node, the NestJS framework takes it to a whole new level, providing state-of-the-art tools for the modern server-side developer to build durable and high-performance applications using components, providers, modules, and other useful high-level abstracts.

In this article, we’ll examine the process of building a simple API server with NestJS, to handle a basic application scenario: creating, storing, and retrieving a list of products for a general store.

If you’d like a copy of the source code for this project, check it out here.

Project Setup

Building with Nest requires a Node environment. If you don’t already have it, head over to their website and download a copy for your OS.

Installing the framework is straightforward:

$ npm i -g @nestjs/cli 

This project was created with the Nest CLI tools by running this command:

$ nest new nest-js-example

This command will create a brand-new Nest project with the required configuration files, folder structure, and server boilerplate.

Application Entry Point

The main file that configures and runs the server is src/main.ts:

This file imports both the NestFactory class used to create the app, along with the main app module file (which we will examine in a moment), and then bootstraps the app by instantiating it and listening to port 3000.

App Module

The file in which app components are declared is src/app.module.ts:

This file serves as the location where the rest of the application components are imported and declared in a Module, which is imported into the previous file we examined (main.ts). The Nest CLI tools will automatically update this file as necessary, when instructed to generate a new component. Here, the controller and service for items are imported and added to the module.

Items Controller

The next file we’ll check out is src/items/items.controller.ts:

This file defines the controller for creating items and retrieving a list of previously created items. Several key components are imported here:

  • CreateItemDto: A Data-Transfer Object that defines how Item data will be sent over the network (i.e. it’s JSON data structure)
  • ItemsService: A Provider that handles manipulating or storing Item data
  • Item: An interface that defines the internal data structure for an Item

The decorator@Controller('items') indicates to the framework that this class will serve the REST endpoint /items, and the constructor for ItemsController takes an instance of ItemsService which it uses internally to service two HTTP methods:

  • POST /items (creates a new item from the request JSON)
  • GET /items (retrieve a list of previously created items)

Requests to these two methods are handled by the create and findAll methods, which are bound to their respective HTTP methods with the @Post() and @Get() decorators. Additional methods can also be supported with decorators in the same way, such as @Put() or @Delete() etc.

Item Object Interfaces

Next up are two files that define interfaces for a store item, one for internal use such as compile-time type-checking (Item), and the external interface for defining the expected structure of the incoming JSON (CreateItemDto):

The Item interface defines three properties for a typical store item: name, description, and price. This ensures there is no confusion within the app design about what an Item is or what properties it has.

The CreateItemDto class reflects the properties in the Item, decorating each property with a @IsNotEmpty() to ensure that all of these properties are required by the REST API endpoint.

All properties for both classes are strongly typed, which is one of the main advantages of TypeScript (hence the name). This improves the level of context understanding at first glance, and greatly reduces development time when used properly with realtime code analysis tools (such as IntelliSense in VSCode). This is especially true on large projects with hundreds or even thousands of different classes and interfaces. For those of us lacking a perfect photographic memory with infinite capacity (such as myself), this is far easier than trying to remember thousands of specific details at will.

The Items Service

Last up is the service for creating and retrieving items, items.service.dart:

The ItemsService class defines a simple array for Item objects that will serve basically as a volatile in-memory datastore for our example project. The two methods which write to, and read from, this “datastore” property are:

  • create (save an Item to the list and return its id)
  • findAll (return the list of previously created Item objects

Testing it Out

To start the server, use the standard npm run start command. Once up and running, the application can be tested by firing HTTP requests from CURL:

$ curl -X POST localhost:3000/items -d '{"name":"trinket", "description":"whatever", "price": 42.0}'

Running this command will return a JSON response with the created item’s id. To view a list of items that have been created already:

$ curl localhost:3000/items

The above GET request to /items will return a JSON response of items currently stored in memory. The output should look something like:

[{"{\"name\":\"trinket\", \"description\":\"whatever\", \"price\": 42.0}":""}]

Conclusion

NestJS is a relative newcomer to the server-side development game, with a great set of features for rapidly building and deploying enterprise-grade services that support the demands of modern app clients, and adhere to principles such as SOLID and the twelve-factor app methodology.

For more information, check out the NestJS website here.

Thanks for checking out my article. Happy coding!

Kenneth Reilly (8_bit_hacker) is CTO of LevelUP

--

--