Preamble
Developers today have many easy options when building other web servieces and server-side applications. Node is a popular choice, but many programmers prefer a stronger language than Javascript, especially those with OOP like C #, C ++ or Java (just a few names). While TypeScript works well with Nodejs, the NestJS framework takes it to the next level, providing the latest and greatest performance for server side development using components, providers, modules, and other components. Other premium features.
In this article, we will look at the process of developing a simple API server with NestJS, handle basic application with: creating, saving, and returning data lists.
Project settings
Building with Nest requires a Node environment. If you do not have it, go to their webside and download it according to the OS
Simple framework installation with command:
1 2 | $ npm i -g @nestjs/cli |
The project will be created with the Nest CLI tool by running the following command:
1 2 | $ nest new nest-js-example |
The above command will create a new Nest project with configuration files, directory structures, and conflicting servers.
Application Entry Point
Main file for configuring and running the server in src/main.ts
:
1 2 3 4 5 6 7 8 9 10 11 | import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap(); |
In the import file 2 NestFactory class is used to create the app, along with the main main module module file. and bootrap is booting up and listening on port 3000.
App Module
Component is declared in src / app.module.ts file:
1 2 3 4 5 6 7 8 9 10 11 12 | import { Module } from '@nestjs/common'; import { ItemsController } from './items/items.controller'; import { ItemsService } from './items/items.service'; @Module({ imports: [], controllers: [ ItemsController ], providers: [ ItemsService ], }) export class AppModule {} |
In this file server acts as the component declaration of the application and import a module, it imports into the file we have previously reviewed. The Nest cli will automatically update and update this file as needed, when creating a new component. Below is a controller and services for itmes imported and added to the module.
Items Controller
The next file we look for is src/items/ítems.controller.ts
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import { Controller, Req, Get, Post, Body } from '@nestjs/common' import { CreateItemDto } from './dto/create-item.dto' import { ItemsService } from './items.service' import { Item } from './items.interface' @Controller('items') export class ItemsController { constructor(private readonly itemsService: ItemsService) {} @Post() create(@Body() data: CreateItemDto): Object { return this.itemsService.create(data) } @Get() findAll(): Array<Item> { return this.itemsService.findAll() } } |
In this file define controller to create items and display a list after creating those items. Some of the main ingredients are listed below:
- CreateItemDto: A data transfer object that defines how Item data will be sent to the network
- ItemsService: A Provider that processes and stores Item data.
- Item: an interface that defines the data structure for an Item. An
@Controller('itmes')
decorator@Controller('itmes')
indicates that the framework for the REST endpoit class is / items, and the ItemController search structure takes ItemsServices and uses two methods. - Post / items
- Get / items Request to these 2 methods will be handled by create and findAll methods, and bound by HTTP methods with @Post () and @Get . To use methods that are supported with decorators with the same, such as @Put () or @Delete () and so on.
Item Object Interfaces
Item interface defines 3 properties of the item in the store: name, details, and price. This ensures no confusion with the design of the app.
1 2 3 4 5 6 7 | export interface Item { name: string, description: string, price: number } |
The CreateItemDto class reflects the properties of Items, each property has an @IsNotEmpty () decorator that ensures all of them are required in the REST API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import { IsNotEmpty } from 'class-validator'; export class CreateItemDto { @IsNotEmpty() readonly name: string; @IsNotEmpty() readonly description: string; @IsNotEmpty() readonly price: number; } |
Items Service
Finally the service to create and return items, items.service.dart:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import { Injectable } from '@nestjs/common' import { Item } from './items.interface' @Injectable() export class ItemsService { private items: Array<Item> = [] create(item: Item): Object { this.items.push(item) return { id: this.items.length.toString() } } findAll(): Array<Item> { return this.items; } } |
Testing it Out
Run the server, with the command npm run start
. We can test with the curl command:
1 2 | $ curl -X POST localhost:3000/items -d '{"name":"trinket", "description":"whatever", "price": 42.0}' |
Running the command below will return a JSON after it has been generated
1 2 | $ curl localhost:3000/items |
Data we receive
1 2 | [{"{"name":"trinket", "description":"whatever", "price": 42.0}":""}] |
Reference article https://itnext.io/getting-started-with-nestjs-307556e02c8d