Top JavaScript Frameworks and Libraries to Embrace in 2020

Top JavaScript Frameworks and Libraries to Embrace in 2020

JavaScript frameworks and libraries have proven to be the building block of every website and mobile application these days. These frameworks and libraries, while handling frontend and backend development needs, have helped developers easily build...

JavaScript frameworks and libraries have proven to be the building block of every website and mobile application these days. These frameworks and libraries, while handling frontend and backend development needs, have helped developers easily build a dynamically advanced software - be it real-time chat, inventory, e-commerce, or any other. Today, there's hardly any small and big company who is not including any of the top JavaScript framework/library into their technology stack.

Considering this, if you too are planning to step into the market with the support of a JS framework, but pale confused which one is popular in the market, this article is going to be a good read for you. Here, we will be talking about the top JavaScript frameworks and libraries that will rule the market in 2020, followed by how to pick the best one for your development needs.

So, without ado, let's see the first one

1. Angular

The foremost JavaScript framework that will be used for building interactive web and mobile app user interfaces is Angular. The framework is used both by startups and big corporations due to advantages like:-

  • High-end documentation.
  • Wider ecosystem.
  • Elegant programming style.
  • Availability of full set of tools.
  • Exceptional Performance and Flexibility.

To get in-Depth knowledge on Angularjs you can enroll for a live demo on Angularjs Online Training

2. Vue.js

While many are still wondering why is Vue getting momentum in the mobile market, the framework has entered among the top JS frameworks for 2020 too. The framework, released back in 2014, is ruling the hearts of mobile app developers with a vast range of features and functionalities it offers, including:-

  • Ease of Learning.
  • Flexible development environment.
  • Effective CLI.
  • Option to integrate elements of other languages into the development environment.
  • Facility to build lightweight apps.

3. React.js

Another library that is expected to be widely adopted by app developers for their next project this year is React. Developed and maintained by Facebook, the Reactjs library comes loaded with various must-needed characteristics, such as:

  • Flexibility.
  • Small file size.
  • Simple updates such that stability remains maintained throughout.
  • Option to integrate other libraries, if required.
  • Enhanced efficiency and SEO performance, and more.

To get in-Depth knowledge on Reactjs you can enroll for a live demo on Reactjs Online Training

4. Ember.js

Ember is yet another framework that is becoming popular in the JavaScript world, making both business enthusiasts and developers show an interest in Vue vs Ember battle. The framework is currently used by various reputed brands like Netflix, Square, and Microsoft because of a myriad of benefits it offers. A few of which are:-

  • It empowers developers to integrate templates into the development environment instead of writing lengthy code lines. This lowers down the development timeline and cost.
  • Its abstraction mechanism gives app development agencies an escape from trivial choices and enables them to create a unique app.
  • It comes loaded with various friendly APIs that improves the overall efficiency and productivity.

5. Node.js

Released back in 2008, Node.js is yet another top JavaScript framework to consider in 2020. The framework is open-source, cross-platform, JavaScript runtime environment that enables developers to employ JavaScript for writing command-line tools and server-side scripts, run them outside of a browser, and build dynamic web pages and lightweight apps.

To get in-Depth knowledge on Nodejs you can enroll for a live demo on Nodejs Online Training

6. Backbone.js

Another JavaScript library that will gain huge momentum in 2020 is Backbone. Released back in 2010, this library is based on MVP (Model-View-Presenter) app design paradigm, is lightweight, and is an apt choice for designing single-page web apps and maintain real-time synchronization between different parts of web applications.

7. Express.js

Though Express.js (also called Express) entered the market as a web app framework for Nodejs course, it has slowly and gradually made its distinct presence in the market with features like:-

  • Ease of setting up middlewares to respond to HTTP requests,
  • Ability to design single-page, multi-page, and hybrid web apps,
  • Facility to dynamically render HTML pages depending on passing arguments to templates, etc.
  • This free and open-source framework, as per a survey on The State of JavaScript, is found to be the one that the majority of respondents would like to work with 'again' this year.

8. Redux.js

Redux library is widely used for managing the state of an application and enjoying benefits like higher debugging facilities, enhances flexibility, ease of updating the indicators and visual information of users regularly, compatibility with React, and more. And in 2020, the library is expected to get more popular among developers to build high-quality apps. While these are the javascript frameworks and libraries that will enjoy the limelight this year, there are many that will play the game behind the curtains. So, let's have a look at some of them before making a remarkable decision of picking the right one.

9. GraphQL

Released back in 2015, this JavaScript library is also attracting various developers these days. In fact, it has been found that 62% of respondents in a survey have admitted to being familiar with this library and planning to learn about it in the future.

Something that is a consequence of ample of functionalities and advantages it offers, with the prime one being the opportunity to be specific about which data is required and how to combine data from different sources before downloading it from the server.

10. Svelte

Developed by Rich Harris in 2016, Svelte is another framework that is expected to gain recognition in the JavaScript world this year. The component framework enables write small code line. Also, unlike React and other traditional frameworks, it does not rely upon techniques like Virtual DOM diffing for its operation. Rather, it runs at build time and converts components into highly efficient imperative code that updates the DOM precisely. This way, it enables developers to write ambitious and complex applications with an exquisite performance level.

Conclusion

Now as you know the top javascript frameworks for 2020, you must be curious to find an answer to the question, "Which one is best to pick among them?". Well, there is no exact answer.

This is so because how a framework/library performs depends on several factors, like your software development needs, your hired app development company, the type of additional tools you connect, and more. So, it is advised to bring your team on board, be open about your app needs, and then choose the javascript framework that suits to your requirements.

Top Collection NodeJS Frameworks for Developers in 2020

Top Collection NodeJS Frameworks for Developers in 2020

Node.js is an open-source, cross-platform runtime environment built on Chrome’s V8 javascript engine. The event-driven, non-blocking I/O model makes the NodeJS framework an extremely lightweight and efficient web application.

Node.js is an open-source, cross-platform runtime environment built on Chrome’s V8 javascript engine. The event-driven, non-blocking I/O model makes the NodeJS framework an extremely lightweight and efficient web application.

As a developer, one gets to smoothly use the same language for both client–side and server–side scripting and this unique facility has increased the quick adoption of NodeJS frameworks by many developers across the globe in building web applications of any size.

Since it’s been launched in 2009 as a tool for building scalable, server-side web applications it has brought about exponential growth in its usage.

In addition, Node facilitates quick prototyping in building unique projects.

Let’s check out this list of 10 Top NodeJS Frameworks:

1. Hapi.JS

Hapi is a powerful and robust framework that is used for developing APIs. The well-developed plugin system and various key features such as input validation, configuration-based functionality, implement caching, error handling, logging, etc. make the Hapi one of the most preferred frameworks. It is used for building useful applications and providing technology solutions by several large-scale websites such as PayPal, Disney.

Hapi builds secure, powerful, and scalable applications with minimal overhead and out-of-the-box functionality

Hapi is a configuration-driven model built to control web server operations. It has the unique function of being able to create a server on a specific IP , and has functions such as " onPreHandler ", we can process the request by intercepting the request and preprocessing the request before it is completed.

2. Express.JS

Express.js was built by TJ Holowaychuk, one of the members of the core Node project team. A large community backs this framework, so it has the advantages of continuous updates and reforms of all the core features. This is a minimalist framework that is used to build a number of mobile applications and APIs.

Express is a minimal and flexible Node.JS web application framework providing a robust set of features

It’s robust API allows users to configure routes to send/receive requests between the front-end and the database (acting as a HTTP server framework).

A good advantage with express is how it supports a lot of other packages and other template engines such as Pug, Mustache, EJS and a lot more.

3. Socket.io

It is used for building real-time web applications. It’s a Javascript library that allows the bidirectional data flow between the web client and server. Asynchronous data I/O, binary streaming, instant messaging are some of the most important features of this framework.


Socket the fastest and reliable real-time engine

4. Total.JS

Total.js is a modern and modular NodeJS supporting the MVC architecture. Angular.js, Polymer, Backbone.js, Bootstrap and other client–side frameworks are fully compatible with this framework. This framework is totally extensible and asynchronous. The fact that it does not require any tools such as Grunt to compress makes it easy to use. It also has NoSql embedded in it and supports array and other prototypes.

Total.js has some really beautiful versions like the Total.js Eshop, which contains a user interface optimized for mobile devices, and it is downloadable by all premium members. Eshop is one of the best Node.js e-commerce system. This is because of its many versions of unique content management system(CMS).

5. Sail.JS

This MVC framework has become very popular with NodeJS developers and this framework has gained traction through the development of chat applications, dashboards and multiplayer games. It is most famous for building data-driven APIs. It uses waterline for object-related mapping and db solutions. This framework uses Express.js for handling HTTP requests and is built upon Node.js.

Its compatibility with Grunt modules, including LESS, SASS, Stylus, CoffeeScript, Jade, Dust makes it an ideal candidate for browser-based applications.

Sail is highly compatible with several front-end platforms. Developers have enough freedom to their development while implementing this framework.

6. Derby

This is an MVC framework that is used for creating real-time mobile and web applications. Derby’s Racer, a real-time data synchronization engine for Node.js allows multi-site, real-time concurrency and data synchronization across clients and servers. The racer optimizes conflict resolution and allows real-time editing of the application by leveraging the ShareJS.

Derby is a full-stack framework for writing modern web applications

Derby is an open-source framework based on MVC structure and it is a full-stack NodeJS web framework. Derby is considered ideal for developing real-time collective applications. Using DerbyJS , developers can easily add customized codes and build real-time and effective custom made websites.

7. Meteor.JS

One of the fundamentally most used NodeJS frameworks is Meteor.JS. And this list would remain incomplete if we didn’t mention the MeteorJS framework. This is a full-stack framework of NodeJS which allows users to build real-time applications.

It is used to create both mobile and web-based javascript applications.

Backed by a huge community of developers, tutorials, custom packages and documentation, this framework is used to create some great web and mobile applications for only Javascript only.

8. Loopback

Loopback is a highly-extensible API framework that allows the user to create such APIs that can work with any kind of web client and can be easily bridged to backend sources. This new age modern application comes with complex integration. With Loopback being an open-source framework, the user can create dynamic REST APIs with a minimum or no knowledge of coding.

Highly extensible NodeJS framework for building APIs and microservices

Loopback permits developers to create SDKs and API documentation. This is possible due to widget-API explorer that comes in default with loopback.

Also, it comes with model-relation-support, third party login and storage service, API swagger, better user management policy

9. Koa

Koa was created by the same team that created Express.js and it is often referred to as the next-generation NodeJS framework. Koa is unique in the fact that it uses some really cool ECMAScript(ES6) methods that have not even landed in some browsers yet. It allows you to work without callbacks while providing you with an immense increase in error handling.

It requires a NodeJS version of at least 0.11 or higher.

KoaJS supports syn/await keywords and helps to manage the codes neatly.

Also, it doesn’t pack any bundle of middleware in the core. That makes server writing with Koa faster and enjoyable. KoaJS comes with more options for customization. It allows you to work with applications from scratch where developers can add those features only which they need.

10. NestJS

NestJs is a framework built with Node.js, It is used for building efficient, scalable Node.js server-side applications. Nest uses progressive JavaScript and is written with TypeScript. Being built with TypeScript means that Nest comes with strong typing and combines elements of OOP(Object Oriented Programming), FP(Functional Programming) and FRP(Functional Reactive Programming).

Advantages of the NodeJS framework

NodeJS Framework is now emerging as the most commonly used development framework for building frontend and backend for web applications. And it is the most preferred environment for custom web development. Let’s check some of the major advantages of NodeJS Framework:

  • Real-time working environment
  • Simple coding experience
  • Seamless data streaming
  • Same code pattern throughout development
  • User-friendly
Final analysis

After reading this article, we can of course understand that which framework to use depends entirely on the type of website and web application we want to build. The list of frames is endless and is everywhere in the JavaScript community.

Why ReactJS is better for Web Application Development?

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

Web Application Development is essential for a business in today’s digital era. Finding the right platform for Web Application Development is important for building an effective Web Application that can enhance the overall customer engagement. Here’s what makes ReactJS a better option for building your next Web Application.

NodeJs Development with framework fortjs

NodeJs Development with framework fortjs

Nodejs gives you the power to write server side code using JavaScript. In fact, it is very easy and fast to create a web server using Nodejs. There are several frameworks available on Node package manager which makes the development even easier...

Nodejs gives you the power to write server side code using JavaScript. In fact, it is very easy and fast to create a web server using Nodejs. There are several frameworks available on Node package manager which makes the development even easier and faster.

But there are a few challenges in Nodejs development:

  • Nodejs is all about callbacks, and with more and more callbacks you end up with a situation called callback hell.
  • Writing readable code.
  • Writing maintainable code.
  • You don't get much intellisense support which makes development slow.

If you are quite experienced and have a good knowledge of Nodejs, you can use different techniques and try to minimize these challenges.

The best way to solve these problems is by using modern JavaScript ES6, ES7 or TypeScript, whatever you feel comfortable with. I recommend TypeScript, because it provides intillisense support for every word of code which makes your development faster.

So I created a framework called FortJs which is very easy to learn and use. FortJs enables you to write server-side code using ES6 or TypeScript which is modular, secure, and pretty much just beautiful and readable.

Features

Some of the important features of FortJs are:

  • Based on Fort architecture.
  • MVC Framework and follows OOPS approach so everything is class and object.
  • Provides components - Wall, Shield and Guard. Components help modularize the application.
  • Uses ES6 async/await or promise for executing asychronous code.
  • Everything is configurable - you can configure your session store, view engine, websocket etc.
  • Dependency Injection.
  • Everything can be unit tested, so you can use a TDD approach.
Let's Code

In this article I am going to create a REST API using FortJs and ES6. But you can use the same code and steps to implement using TypeScript too.

Project Setup

FortJs provides a CLI - fort-creator. This helps you set up the project and develop faster. Let's use the CLI to develop.

Perform the below steps sequentially:

  • Open your terminal or command prompt.
  • Install FortJs globally - run the command "npm i fort-creator -g". Note: Make sure you have Nodejs installed in your system.
  • Create a new project - run the command "fort-creator new my-app". Here “my-app” is the name of the app, so you can choose any name. The CLI will prompt you to choose the language with two options: TypeScript and JavaScript. Choose your language by using the arrow keys and press enter. Since I'm going to use ES6, I have chosen JavaScript. It will take some time to create the project, so please wait until you see "new project my-app created".
  • Enter into the project directory - "cd my-app".
    Start the development server with live reloading - run the command "fort-creator start".
  • Open the browser and type the URL - http://localhost:4000/.

You should see something like this in the browser.

Let's understand how this page is rendered:

  • Open the project folder in your favourite code editor. I am going to use VS Code. You will see many folders inside project root such as controllers, views, etc. Every folder is grouped by their use - for example, the controllers folder contains all controllers and the views folder contains all views.

  • Open the controllers folder -> Inside the controllers, you will see a file name - default_controller. Let's open it and observe the code. The file contains a class DefaultController - this is a controller class and it contains methods which return some http response.

  • Inside the class DefaultController, you will see a method 'index' - this is the one which is rendering current output to the browser. The method is known as worker in FortJs because they do some kind of work and return the result as an http response. Let's observe the index method code:

    const data = {
       title: title
    }
    const result = await viewResult('default/index.html', data);
    return result;
    

    It creates a data object and passes that object into the viewResult method. The viewResult method takes two parameters - the view location and view data. The work of viewResult is to render the view and return a response, which we are seeing in the browser.

  • Let's find the view code and understand it. Open the views folder - > open default folder - > open index.html. This is our view code. It is simple HTML code along with some mustache syntax. The default view engine for Fortjs is mustache.

I hope you have understood the project architecture. If you are having any difficulties or doubts, please feel free to ask in the comments section.

Now we will move to next part of this article where we will learn how to create a simple rest API.

REST

We are going to create a REST endpoint for entity user - which will perform CRUD operations for the user such as adding a user, deleting a user, getting a user, and updating a user.

According to REST:

  1. Adding user - should be done using the http method "POST"
  2. Deleting user - should be done using the http method "REMOVE"
  3. Getting user - should be done using the http method "GET"
  4. Updating user - should be done using the http method "PUT"

For creating an endpoint, we need to create a Controller similar to the default controller explained earlier.

Execute the command  "fort-creator add". It will ask you to "Choose the component to add ?" Choose Controller & press enter. Enter the controller name "User" and press enter.

Now that we have created the user controller we need to inform FortJs by adding it to routes. The route is used to map our controller to a path.

Since our entity is user, "/user" will be a good route. Let's add it. Open routes.js inside the root directory of the project and add UserController to routes.

After adding UserController, routes.js will look like this:

import { DefaultController } from "./controllers/default_controller";
import { UserController } from "./controllers/user_controller";

export const routes = [{
    path: "/*",
    controller: DefaultController
},
{
    path: "/user",
    controller: UserController
}]

routes.js

So when an http request has the path "/user" then UserController will be called.

Let's open the url - http://localhost:4000/user.

Note: If you have stopped FortJs while adding the controller, please start it again by running the cmd - fort-creator start

And you see a white page right?

This is because we are not returning anything from the index method and thus we get a blank response. Let's return a text "Hello World" from the index method. Add the below code inside the index method and save:

return textResult('Hello World');

Refresh the url - http://localhost:4000/user

And you see "Hello World" right?

Now, let's convert "UserController" to a REST API. But before writing code for the REST API, let's create a dummy service which will do CRUD operations for users.

Service

Create a folder called “services” and then a file “user_service.js” inside the folder. Paste the below code inside the file:

const store = {
    users: [{
        id: 1,
        name: "ujjwal",
        address: "Bangalore India",
        emailId: "[email protected]",
        gender: "male",
        password: "admin"
    }]
}

export class UserService {
    getUsers() {
        return store.users;
    }

    addUser(user) {
        const lastUser = store.users[store.users.length - 1];
        user.id = lastUser == null ? 1 : lastUser.id + 1;
        store.users.push(user);
        return user;
    }

    updateUser(user) {
        const existingUser = store.users.find(qry => qry.id === user.id);
        if (existingUser != null) {
            existingUser.name = user.name;
            existingUser.address = user.address;
            existingUser.gender = user.gender;
            existingUser.emailId = user.emailId;
            return true;
        }
        return false;
    }

    getUser(id) {
        return store.users.find(user => user.id === id);
    }

    removeUser(id) {
        const index = store.users.findIndex(user => user.id === id);
        store.users.splice(index, 1);
    }
}

The above code contains a variable store which contains a collection of users. The method inside the service does operations like add, update, delete, and get on that store.

We will use this service in REST API implementation.

GET

For the route "/user" with the http method "GET", the API should return a list of all users.

In order to implement this, let's rename the "index" method inside user_controller.js to "getUsers" making it semantically correct. Then paste the below code inside the method:

const service = new UserService();
return jsonResult(service.getUsers());

Now user_controller.js looks like this:


import { Controller, DefaultWorker, Worker, textResult, jsonResult } from "fortjs";
import { UserService } from "../services/user_service";

export class UserController extends Controller {

    @DefaultWorker()
    async getUsers() {
        const service = new UserService();
        return jsonResult(service.getUsers());
    }
}

Here, we are using the decorator DefaultWorker. The DefaultWorker does two things: it adds the route "/" & the http method "GET". It's a shortcut for this scenario. In the next part, we will use other decorators to customize the route.

Let's test this by calling the url http://localhost:4000/user. You can open this in the browser or use any http client tools like postman or curl.

Ok, so we have successfully created an end point :) .

Let's look again at our code and see if we can make it better:

  1. The service "UserService" is tightly coupled with Controller "UserController" which becomes a problem for unit testing "UserController". So we will use dependency injection by FortJs to inject UserService.
  2. We are creating an instance of "UserService" every time the method getUsers is called. But what we need from "UserService" is a single object and then call the "UserService" method from the object.

So if we can somehow store an object of "UserService" then we can make our code faster (because calling new does some work under the hood). For this we will use the singleton feature of FortJs.

Let's change the user_controller.js code by the below code:


import { Controller, DefaultWorker, Worker, textResult, jsonResult, Singleton } from "fortjs";
import { UserService } from "../services/user_service";

export class UserController extends Controller {

    @DefaultWorker()
    async getUsers(@Singleton(UserService) service) {
        return jsonResult(service.getUsers());
    }
}

As you can see, the only change is that we are using the "Singleton" decorator in the method getUsers. This will create a singleton and inject that singleton when getUsers is called. This singleton will be available throughout the application.

Since service is now a parameter, we can manually pass the parameter while calling. This makes getUsers unit testable.

For doing unit testing or E2E testing, please read this test doc - http://fortjs.info/tutorial/test/

POST

Let's add a method "addUser" which will extract data from the request body and call service to add a user.

async addUser(@Singleton(UserService) service) {
        const user = {
            name: this.body.name,
            gender: this.body.gender,
            address: this.body.address,
            emailId: this.body.emailId,
            password: this.body.password
        };
        const newUser = service.addUser(user);
        return jsonResult(newUser, HTTP_STATUS_CODE.Created);
}

In the above code we are creating the Singleton of the UserService again. So the question is will it create another object?

No it will be same object that was in getUser. FortJs supplies the object as a parameter when it calls the method.

The methods created are by default not visible for an http request. So in order to make this method visible for the http request, we need to mark this as a worker.

A method is marked as a worker by adding the decorator "Worker". The Worker decorator takes a list of http methods and makes that method available for only those http methods. So let's add the decorator:

@Worker([HTTP_METHOD.Post])
async addUser(@Singleton(UserService) service) {
    const user = {
        name: this.body.name,
        gender: this.body.gender,
        address: this.body.address,
        emailId: this.body.emailId,
        password: this.body.password
    };
    const newUser = service.addUser(user);
    return jsonResult(newUser, HTTP_STATUS_CODE.Created);
}

Now the route of this method is the same as the name of the method that is "addUser". You can check this by sending a post request to http://localhost:4000/user/addUser with user data in the body.

But we want the route to be "/", so that it will be a rest API. The route of the worker is configured by using the decorator "Route". Let's change the route now.

@Worker([HTTP_METHOD.Post])
@Route("/")
async addUser(@Singleton(UserService) service) {
    const user = {
        name: this.body.name,
        gender: this.body.gender,
        address: this.body.address,
        emailId: this.body.emailId,
        password: this.body.password
    };
    const newUser = service.addUser(user);
    return jsonResult(newUser, HTTP_STATUS_CODE.Created);
}

Now our end point is configured for a post request. Let's test this by sending a post request to http://localhost:4000/user/ with user data in the body.

It returns the user created with id which is our logic. So we have created the end point for the post request, but one important thing to do is to validate the data. Validation is an essential part of any app and is very important for a backend application.

So far, our code is clean and readable. But if we add validation code it will become a little dirty.

Worry not, FortJs provides the component Guard for this kind of work. A/c to the FortJs docs:

Guard is security layer on top of Worker. It controls whether a request should be allowed to call the Worker.

So we are going to use guard for validation of the data. Let's create the guard using fort-creator. Execute the command  fort-creator add and choose Guard. Enter the file name "UserValidator". There will be a file "user_validator_guard.js" created inside the guards folder. Open that file.

A guard has access to the body, so you can validate the data inside that. Returning null inside the method check means that we're allowing to call the worker. Returning anything else means block the call.

Let's make it clearer by writing code for the validation. Paste the below code inside the file "user_validator_guard.js":


import { Guard, textResult, HTTP_STATUS_CODE } from "fortjs";

export class UserValidatorGuard extends Guard {

    async check() {
        const user = {
            name: this.body.name,
            gender: this.body.gender,
            address: this.body.address,
            emailId: this.body.emailId,
            password: this.body.password
        };
        const errMsg = this.validate(user);
        if (errMsg == null) {
            // pass user to worker method, so that they dont need to parse again  
            this.data.user = user;
            // returning null means - guard allows request to pass  
            return null;
        } else {
            return textResult(errMsg, HTTP_STATUS_CODE.BadRequest);
        }
    }

    validate(user) {
        let errMessage;
        if (user.name == null || user.name.length < 5) {
            errMessage = "name should be minimum 5 characters"
        } else if (user.password == null || user.password.length < 5) {
            errMessage = "password should be minimum 5 characters";
        } else if (user.gender == null || ["male", "female"].indexOf(user.gender) < 0) {
            errMessage = "gender should be either male or female";
        } else if (user.emailId == null || !this.isValidEmail(user.emailId)) {
            errMessage = "email not valid";
        } else if (user.address == null || user.address.length < 10) {
            errMessage = "address length should be greater than 10";
        }
        return errMessage;
    }

    isValidEmail(email) {
        var re = /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
    }

}

In the above code:

  • We have created a method validate which takes the parameter user. It validates the user & returns the error message if there is a validation error, otherwise null.
  • We are validating data inside the check method, which is part of guard lifecycle. We are validating the user inside it by calling the method validate.
    If the user is valid, then we are passing the user value by using the "data" property and returning null. Returning null means guard has allowed this request and the worker should be called.
  • If a user is not valid, we are returning an error message as a text response with the HTTP code "Bad Request". In this case, execution will stop here and the worker won't be called.

In order to activate this guard for the method addUser, we need to add this on top of addUser. The guard is added by using the decorator "Guards". So let's add the guard:

@Worker([HTTP_METHOD.Post])
@Route("/")
@Guards([UserValidatorGuard])
async addUser(@Singleton(UserService) service) {
    const newUser = service.addUser(this.data.user);
    return jsonResult(newUser, HTTP_STATUS_CODE.Created);
}

In the above code:

  • I have added the guard, “UserValidatorGuard” using the decorator Guards.
  • With the guard in the process, we don't need to parse the data from the body anymore inside the worker. Rather, we are reading it from this.data which we are passing from "UserValidatorGuard".
  • The method “addUser” will only be called when Guard allows, which means all data is valid.

One thing to note is that the method "addUser" looks very light after using a component, and it's doing validation too. You can add multiple guards to a worker which gives you the ability to modularize your code into multiple guards and use that guard at multiple places.

Isn't this cool :D?

Let's try adding a user with some invalid data:

As you can see in the screenshot, I have tried sending a request without a password. The result is - "password should be minimum 5 characters". So it means that guard is activated and working perfectly.

PUT

Let’s add another method - “updateUser” with route “/” , guard “UserValidatorGuard” (for validation of user) and most important - worker with http method “PUT”.

@Worker([HTTP_METHOD.Put])
@Guards([UserValidatorGuard])
@Route("/")
async updateUser(@Singleton(UserService) service) {
    const user = this.data.user;
    const userUpdated = service.updateUser(user);
    if (userUpdated === true) {
        return textResult("user updated");
    } else {
        return textResult("invalid user");
    }
}

The updated code is similar to the addUser code except functionality wise it is updating the data. Here, we have reutilized UserValidatorGuard to validate data.

DELETE

In order to delete data, user needs to pass the id of the user. This can be passed by:

  • Sending data in body just like we did for add & update - {id:1}
  • Sending data in query string - ?id=1
  • Sending data in route - for this, we need to customize our route - "/user/1"

We have already implemented getting data from body. So let's see other two ways:

Sending Data in Query String

Let's create a method "removeByQueryString" and paste the below code:

@Worker([HTTP_METHOD.Delete])
@Route("/")
async removeByQueryString(@Singleton(UserService) service) {
    // taking id from query string
    const userId = Number(this.query.id);
    const user = service.getUser(userId);
    if (user != null) {
        service.removeUser(userId);
        return textResult("user deleted");
    } else {
        return textResult("invalid user", 404);
    }
}

Sending Data in Route

You can parameterise the route by using "{var}" in a route. Let's see how.

Let's create another method "removeByRoute" and paste the below code:

@Worker([HTTP_METHOD.Delete])
@Route("/{id}")
async removeByRoute(@Singleton(UserService) service) {

    // taking id from route
    const userId = Number(this.param.id);

    const user = service.getUser(userId);
    if (user != null) {
        service.removeUser(userId);
        return textResult("user deleted");
    } else {
        return textResult("invalid user");
    }
}

The above code is exactly the same as removeByQueryString except that it is extracting the id from the route and using parameter in route i.e., "/{id}" where id is parameter.

Let's test this:

So we have finally created a REST API for all the funtionalities except GETting a particular user by id. I will leave that to you for practice.

POINTS OF INTEREST

Q: How do we add authentication to "UserController", so that any unauthenticated request can't call the "/user" end point.

A: There are multiple approaches for this:

  • We can check in every worker for authentication. (BAD - so much extra work and code repetition)
  • Create a Guard component and assign to every worker . (GOOD)
  • Create a Shield component and assign to controller. Shield is a security layer similar to guard but works on top of controller, so if shield rejects then controller is not initiated. (BEST)

Take a look at the FortJs authentication docs - http://fortjs.info/tutorial/authentication/