Developing REST API Framework using TypeScript and NestJS

Developing REST API Framework using TypeScript and NestJS

Nowadays, web applications are being designed with REST API and front-end. For developing a UI application, now, we have so many popular JavaScript frameworks available, like Angular, React, Vue and many more. For developing REST API, we have multiple options too. If we select Java as a programming language, we have Spring boot; for .NET, we have REST API Framework; if we choose JavaScript, then we have ExpressJS, HapiJS, and NestJS etc

Nowadays, web applications are being designed with REST API and front-end. For developing a UI application, now, we have so many popular JavaScript frameworks available, like Angular, React, Vue and many more. For developing REST API, we have multiple options too. If we select Java as a programming language, we have Spring boot; for .NET, we have REST API Framework; if we choose JavaScript, then we have ExpressJS, HapiJS, and NestJS etc. Here, I will walk you through Nest.js (https://docs.nestjs.com/). We will learn to build a web application using TypeScript for REST API.

Environment setup

First, install the Nest.js CLI on your local machine using the command:

npm i -g @nestjs/cli

Create a new application.

_nest new _

After this command, it will ask for some basic information, like description, author, and version. Then only the installation gets started.

The installation will take 3-5 minutes typically to complete.

cd sample-nestjs-app and npm run start

Using this command, we can easily start the application.

This application is running on default port 3000.

Understanding Nest.js

Now, let us try to understand what are the different files available and what is the application execution flow NestJS. For this purpose, we have to open the application in an IDE, like Visual Studio Code or Atom.

The above image is showing the list of files and folders in our Nest.js application. We will go through these one-by-one.

Package.json

Those who are aware of any node.js based application are already aware of the use of the package.json file. Here, we will try to understand the packages and commands related to NestJS.

"dependencies": {  
   "@nestjs/common": "^5.4.0",  
   "@nestjs/core": "^5.4.0",  
   "reflect-metadata": "^0.1.12",  
   "rimraf": "^2.6.2",  
   "rxjs": "^6.2.2",  
   "typescript": "^3.0.1"  
 }  

nestjs/common and nestjs/core are basically for NestJS dependencies.

RxJS is a library for reactive programming used for Observables, to make it easier for composing asynchronous or callback-based code.

TypeScript mainly is required as NestJS builds a TypeScript based application.

"scripts": {  
   "build": "tsc -p tsconfig.build.json",  
   "format": "prettier --write \"src/**/*.ts\"",  
   "start": "ts-node -r tsconfig-paths/register src/main.ts",  
   "start:dev": "nodemon",  
   "start:debug": "nodemon --config nodemon-debug.json",  
   "prestart:prod": "rimraf dist && npm run build",  
   "start:prod": "node dist/main.js",  
   "lint": "tslint -p tsconfig.json -c tslint.json",  
   "test": "jest",  
   "test:watch": "jest --watch",  
   "test:cov": "jest --coverage",  
   "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",  
   "test:e2e": "jest --config ./test/jest-e2e.json"  
 }  

These scripts are optional to run multiple options like run the application, build the application, run the unit tests, or run the e2e test cases.

tsconfig.json is mainly used for TypeScript compilation into JavaScript.

Those not having an understanding of TypeScript must first go through https://www.typescriptlang.org/. Here, you will get detailed information about TypeScript.

nodemon.json

{  
"watch": ["src"],  
"ext": "ts",  
"ignore": ["src/**/*.spec.ts"],  
"exec": "ts-node -r tsconfig-paths/register src/main.ts"  }

Nodemon is a utility that will monitor the changes, if any, in your source and automatically restart your server.

Exec command calling main.ts

src folder

We have so many files available inside the src folder. This is a very important part of our application.

Main.ts

import { NestFactory } from '@nestjs/core';  
import { AppModule } from './app.module';  
  
async function bootstrap() {  
 const app = await NestFactory.create(AppModule);  
 await app.listen(3000);  
}  
bootstrap();  

Here, bootstrap method contains 2 lines only.

First line : const app = await NestFactory.create(AppModule); 

NestFactory.create needs to pass the AppModule.

Second line : await app.listen(3000);

Here, 3000 is the port number. In case one needs to change the application port, then change 3000 to any other port number.

app.module.ts

import { Module } from '@nestjs/common';  
import { AppController } from './app.controller';  
import { AppService } from './app.service';  
  
@Module({  
 imports: [],  
 controllers: [AppController],  
 providers: [AppService],  
})  
export class AppModule {}  

app.module is having three main components.

  • Imports
    This is mainly having an array of all imported modules that need to get specified.

  • controllers Here, we need to add all controllers (We will have more information about controllers and services below).

  • Providers It is an array of services that need to be specified.

app.controller.ts

import { Controller, Get } from '@nestjs/common';  
import { AppService } from './app.service';  
  
@Controller()  
export class AppController {  
 constructor(private readonly appService: AppService) {}  
  
 @Get()  
 getHello(): string {  
   return this.appService.getHello();  
 }  
}  

Controller is the main component which exposes all methods to the external world -  like GET, POST, PUT, and Delete.

But we need to specify the actual logic in a service which we are importing in our controller and call the expected function. The service is injected in the constructor.

constructor(private readonly appService: AppService) {}  

App.service.ts

import { Injectable } from '@nestjs/common';  
  
@Injectable()  
export class AppService {  
 getHello(): string {  
   return 'Hello World!';  
 }  
}  

Service class is where the actual functionality/validation or database call is specified.

getHello(): string {  
   return 'Hello World!';  
 }  

This is a simple method which is returning a text value. But you can write any kind of complex logic and return the object as per your requirement.

CLI Commands

A list of available architecture components.

  • class (alias: cl)
  • controller (alias: co)
  • decorator (alias: d)
  • exception (alias: e)
  • filter (alias: f)
  • gateway (alias: ga)
  • guard (alias: gu)
  • interceptor (alias: i)
  • middleware (alias: mi)
  • module (alias: mo)
  • pipe (alias: pi)
  • provider (alias: pr)
  • service (alias: s)

nest generate service users or nest g s users

nest generate class employee or nest g c employee

This way we can directly create required components in our application

Testing

We can have both testing options available - Unit testing and e2e testing.

app.controller.spec.ts

This is a sample test class created. This includes unit test cases for app.controller and app.service.

import { Test, TestingModule } from '@nestjs/testing';  
import { AppController } from './app.controller';  
import { AppService } from './app.service';  
  
describe('AppController', () => {  
 let appController: AppController;  
  
 beforeEach(async () => {  
   const app: TestingModule = await Test.createTestingModule({  
     controllers: [AppController],  
     providers: [AppService],  
   }).compile();  
  
   appController = app.get<AppController>(AppController);  
 });  
  
 describe('root', () => {  
   it('should return "Hello World!"', () => {  
     expect(appController.getHello()).toBe('Hello World!');  
   });  
 });  
});  

This is a jest test case. We can write multiple test cases as per the functionality and to run the unit test cases, npm test. For this purpose, the jest framework is used.

For e2e test, a separate test folder gets created and app.e2e-spec.ts is its sample file.

import { Test, TestingModule } from '@nestjs/testing';  
import * as request from 'supertest';  
import { AppModule } from './../src/app.module';  
  
describe('AppController (e2e)', () => {  
 let app;  
  
 beforeEach(async () => {  
   const moduleFixture: TestingModule = await Test.createTestingModule({  
     imports: [AppModule],  
   }).compile();  
  
   app = moduleFixture.createNestApplication();  
   await app.init();  
 });  
  
 it('/ (GET)', () => {  
   return request(app.getHttpServer())  
     .get('/')  
     .expect(200)  
     .expect('Hello World!');  
 });  
});  

To run e2e tests, the command is

npm run test:e2e

Summary

In this article, we learned some basics of NestJS. When we are talking about NestJS, there are some advanced concepts involved too, like Middleware, Exception, Filters, Pipes, Guards, and Interceptors. Follow my upcoming article on these advanced topics.

I have uploaded the code on GitHub also.

Thank you !

How to Build a REST API Framework using TypeScript and NestJS

How to Build a REST API Framework using TypeScript and NestJS

In this post, we'll learn to build How to Build a REST API Framework using TypeScript and NestJS

Web applications are being designed with REST API and front-end. For developing a UI application, now, we have so many popular JavaScript frameworks available, like Angular, React, Vue and many more. For developing REST API, we have multiple options too. If we select Java as a programming language, we have Spring boot; for .NET, we have REST API Framework; if we choose JavaScript, then we have ExpressJS, HapiJS, and NestJS etc. Here, I will walk you through Nest.js (https://docs.nestjs.com/). We will learn to build a web application using TypeScript for REST API.

Environment setup

First, install the Nest.js CLI on your local machine using the command:

npm i -g @nestjs/cli

Create a new application.

_nest new _

After this command, it will ask for some basic information, like description, author, and version. Then only the installation gets started.

The installation will take 3-5 minutes typically to complete.

cd sample-nestjs-app and npm run start

Using this command, we can easily start the application.

This application is running on default port 3000.

Understanding Nest.js

Now, let us try to understand what are the different files available and what is the application execution flow NestJS. For this purpose, we have to open the application in an IDE, like Visual Studio Code or Atom.

The above image is showing the list of files and folders in our Nest.js application. We will go through these one-by-one.

Package.json

Those who are aware of any node.js based application are already aware of the use of the package.json file. Here, we will try to understand the packages and commands related to NestJS.

"dependencies": {  
   "@nestjs/common": "^5.4.0",  
   "@nestjs/core": "^5.4.0",  
   "reflect-metadata": "^0.1.12",  
   "rimraf": "^2.6.2",  
   "rxjs": "^6.2.2",  
   "typescript": "^3.0.1"  
 }  

nestjs/common and nestjs/core are basically for NestJS dependencies.

RxJS is a library for reactive programming used for Observables, to make it easier for composing asynchronous or callback-based code.

TypeScript mainly is required as NestJS builds a TypeScript based application.

"scripts": {  
   "build": "tsc -p tsconfig.build.json",  
   "format": "prettier --write \"src/**/*.ts\"",  
   "start": "ts-node -r tsconfig-paths/register src/main.ts",  
   "start:dev": "nodemon",  
   "start:debug": "nodemon --config nodemon-debug.json",  
   "prestart:prod": "rimraf dist && npm run build",  
   "start:prod": "node dist/main.js",  
   "lint": "tslint -p tsconfig.json -c tslint.json",  
   "test": "jest",  
   "test:watch": "jest --watch",  
   "test:cov": "jest --coverage",  
   "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",  
   "test:e2e": "jest --config ./test/jest-e2e.json"  
 }  

These scripts are optional to run multiple options like run the application, build the application, run the unit tests, or run the e2e test cases.

tsconfig.json is mainly used for TypeScript compilation into JavaScript.

Those not having an understanding of TypeScript must first go through https://www.typescriptlang.org/. Here, you will get detailed information about TypeScript.

nodemon.json

{  
"watch": ["src"],  
"ext": "ts",  
"ignore": ["src/**/*.spec.ts"],  
"exec": "ts-node -r tsconfig-paths/register src/main.ts"  }

Nodemon is a utility that will monitor the changes, if any, in your source and automatically restart your server.

Exec command calling main.ts

src folder

We have so many files available inside the src folder. This is a very important part of our application.

Main.ts

import { NestFactory } from '@nestjs/core';  
import { AppModule } from './app.module';  
  
async function bootstrap() {  
 const app = await NestFactory.create(AppModule);  
 await app.listen(3000);  
}  
bootstrap();  

Here, bootstrap method contains 2 lines only.

First line : const app = await NestFactory.create(AppModule);  

NestFactory.create needs to pass the AppModule.

Second line : await app.listen(3000);  

Here, 3000 is the port number. In case one needs to change the application port, then change 3000 to any other port number.

app.module.ts

import { Module } from '@nestjs/common';  
import { AppController } from './app.controller';  
import { AppService } from './app.service';  
  
@Module({  
 imports: [],  
 controllers: [AppController],  
 providers: [AppService],  
})  
export class AppModule {}  

app.module is having three main components.

  • Imports
    This is mainly having an array of all imported modules that need to get specified.

  • controllers Here, we need to add all controllers (We will have more information about controllers and services below).

  • Providers It is an array of services that need to be specified.

app.controller.ts

import { Controller, Get } from '@nestjs/common';  
import { AppService } from './app.service';  
  
@Controller()  
export class AppController {  
 constructor(private readonly appService: AppService) {}  
  
 @Get()  
 getHello(): string {  
   return this.appService.getHello();  
 }  
}  

Controller is the main component which exposes all methods to the external world -  like GET, POST, PUT, and Delete.

But we need to specify the actual logic in a service which we are importing in our controller and call the expected function. The service is injected in the constructor.

constructor(private readonly appService: AppService) {}  

App.service.ts

import { Injectable } from '@nestjs/common';  
  
@Injectable()  
export class AppService {  
 getHello(): string {  
   return 'Hello World!';  
 }  
}  

Service class is where the actual functionality/validation or database call is specified.

getHello(): string {  
   return 'Hello World!';  
 }  

This is a simple method which is returning a text value. But you can write any kind of complex logic and return the object as per your requirement.

CLI Commands

A list of available architecture components.

  • class (alias: cl)
  • controller (alias: co)
  • decorator (alias: d)
  • exception (alias: e)
  • filter (alias: f)
  • gateway (alias: ga)
  • guard (alias: gu)
  • interceptor (alias: i)
  • middleware (alias: mi)
  • module (alias: mo)
  • pipe (alias: pi)
  • provider (alias: pr)
  • service (alias: s)

nest generate service users or nest g s users

nest generate class employee or nest g c employee

This way we can directly create required components in our application

Testing

We can have both testing options available - Unit testing and e2e testing.

app.controller.spec.ts

This is a sample test class created. This includes unit test cases for app.controller and app.service.

import { Test, TestingModule } from '@nestjs/testing';  
import { AppController } from './app.controller';  
import { AppService } from './app.service';  
  
describe('AppController', () => {  
 let appController: AppController;  
  
 beforeEach(async () => {  
   const app: TestingModule = await Test.createTestingModule({  
     controllers: [AppController],  
     providers: [AppService],  
   }).compile();  
  
   appController = app.get<AppController>(AppController);  
 });  
  
 describe('root', () => {  
   it('should return "Hello World!"', () => {  
     expect(appController.getHello()).toBe('Hello World!');  
   });  
 });  
});  

This is a jest test case. We can write multiple test cases as per the functionality and to run the unit test cases, npm test. For this purpose, the jest framework is used.

For e2e test, a separate test folder gets created and app.e2e-spec.ts is its sample file.

import { Test, TestingModule } from '@nestjs/testing';  
import * as request from 'supertest';  
import { AppModule } from './../src/app.module';  
  
describe('AppController (e2e)', () => {  
 let app;  
  
 beforeEach(async () => {  
   const moduleFixture: TestingModule = await Test.createTestingModule({  
     imports: [AppModule],  
   }).compile();  
  
   app = moduleFixture.createNestApplication();  
   await app.init();  
 });  
  
 it('/ (GET)', () => {  
   return request(app.getHttpServer())  
     .get('/')  
     .expect(200)  
     .expect('Hello World!');  
 });  
});  

To run e2e tests, the command is

npm run test:e2e

Summary

In this article, we learned some basics of NestJS. When we are talking about NestJS, there are some advanced concepts involved too, like Middleware, Exception, Filters, Pipes, Guards, and Interceptors. Follow my upcoming article on these advanced topics.

I have uploaded the code on GitHub also.

Thank for reading!

6 Front-End Challenges in 2020

6 Front-End Challenges in 2020

Front-end development is stressful and hard — but with practice, one can master the craft. If you’re willing to put the work and effort in, you’ll be able to become a proficient problem solver in the front-end development landscape. One effective way to become a great front-end developer is to simply build and solve as many challenges as one can. Here Are 6 Front-End Challenges to Code. Are you able to code These front-end challenges?

Front-end development is stressful and hard — but with practice, one can master the craft. If you’re willing to put the work and effort in, you’ll be able to become a proficient problem solver in the front-end development landscape. One effective way to become a great front-end developer is to simply build and solve as many challenges as one can.

Here are six challenges you can start solving today to become a master of front-end development. Without further ado, here are the six challenges you probably should code.

1. Credit Card Form

A fantastic credit card form with smooth and sweet microinteractions. Includes number formatting, validation, and automatic card-type detection. It’s built with Vue.js and also fully responsive.

credit-card-form — https://github.com/muhammederdem/credit-card-form

What you’ll learn by solving the challenge

  • Form handling and validation
  • Handling event listeners (e.g., when the fields change, it’ll print the values on the credit card)
  • Understanding how to display and position elements on the page, especially the credit card overlapping the form
2. Bar Chart From Scratch

A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values they represent.

The bars can be plotted vertically or horizontally. A vertical barchart is sometimes called a line graph.

What you’ll learn by solving the challenge

  • Display data in a structured and easily understandable way
  • Optional: Learn how to use the `` element and how to draw elements with it

You can find the data for the world population by year here.

3. GitHub Repositories With Search Functionality

Nothing out of the world here — GitHub repositories are basically just a glorified list.

The task is to display the repositories and allow the user to filter through the repositories. Use the official GitHub API to fetch repositories per user.

GitHub profile page — https://github.com/indreklasn

What you’ll learn by solving the challenge 4. Twitter Heart Animation

Back in 2016, Twitter introduced this awesome animation for their tweet likes. As of 2019, it still looks rad, so why not create one yourself?

Twitter tweet like animation

What you’ll learn by solving the challenge

  • How the keyframes CSS attribute works
  • How to manipulate and animate HTML elements
  • How to combine JavaScript, HTML, and CSS
5. Reddit-Style Chat Rooms

Chat rooms are a popular way of communicating thanks to being easy and fun to use. But what actually powers modern-day chat rooms? WebSockets!

What you’ll learn by solving the challenge

  • How to use WebSockets and real-time communication and data updates
  • How user permissions levels work (e.g, the owner of a chat channel has the role of admin, while others in the room have the role of user)
  • Form validation and handling — remember, the chat box for sending a message is an input element
  • How to create and join different chat rooms
  • Direct messages and how they work. Users can communicate with other users privately. Essentially, you’ll be establishing a WebSocket connection between two users.
6. Stripe-Style Navigation

What’s unique about this navigation is the popover container morphs to fit the content. There’s an elegance to this transition versus the traditional behavior of opening and closing a new popover entirely.

Stripe navigation

What you’ll learn by solving the challenge

  • How to combine CSS animations with transitions
  • Cross-fading content and applying the active class for the element being hovered

Try doing it first yourself, but if you need help, check out this post for a step-by-step guide.

Conclusion

Remember, there are no shortcuts when it comes to getting good at coding. Start putting the work in, and boost your coding skills by building as much as you can. If you didn’t find anything interesting, check the post below for even more ideas.

Thanks for reading — hope you found something interesting to code.

What TypeScript taught me about JavaScript

What TypeScript taught me about JavaScript

What TypeScript taught me about JavaScript. TypeScript was designed to make the most sense out of any JavaScript code. How void behaves in both TypeScript and JavaScript. What Symbols are and why they can be unique. Why substitutability is such an important concept for TypeScript

TypeScript was designed to make the most sense out of any JavaScript code. Given the dynamic nature of JavaScript, this can lead to some very interesting typings that may seem odd at a first glance. In this talk, we will look at JavaScript scenarios that are easy to understand, but complex to define. We then see what tools TypeScript provides to make the most dynamical behaviour predictable, in the most elegant way possible.

Join us and learn:

  • How void behaves in both TypeScript and JavaScript
  • What Symbols are and why they can be unique
  • The constructor interface pattern, and why classes are more complex than you might think
  • Why substitutability is such an important concept for TypeScript
    ... and much more!