Node.js – tools/packages/practices for building a secure,high performance API with quality code

Contents >Code standard and styling >Security >Performance         In this article, we will take a look at some important aspects to be considered while developing Node.js applications and the tools/packages/practices that can be used to achieve them. Understanding and using these will help you in building a secure web application that is well structured and well documented and has a very high performance. Code standard and styling Tool – Linters(ESLint/JSLint/TSLint) Linters are static code analyzing tools that check for static code issues like styling errors, poorly structured code and unsafe code. Linters help in implementing a certain set of coding rules and helps in avoiding static errors like an absence of strict type checking, mismatched import or undefined variable usage .Static code analysis is analyzing the code for errors/faults in coding rule implementation before running the code. Dynamic code analysis is performed after the running. The most commonly used styling modules are Airbnb/JavaScript and Github/JavaScript.You have to integrate the linting plugin to the editor you are using(eg – Visual Studio Code/Sublime text). The linter will show linting errors like the following.   ESLint and JSLint are used along with JavaScript. TSLint is used with TypeScript. An example…

Using express-validator to validate password to have minimum 8 characters including at least one special character and at least one number

Q How to use express-validator to validate passwords to have minimum 8 characters including at least one special character at least one number? A The regular expression used to validate a password which will follow the above-mentioned pattern is as follows

While using express-validator, we use  the chain method .matches() to check the input password against regular expression as follows

The above validator checks whether the request body of the post request has a password which is a minimum of 8 characters long, and contains an alphabet and a special character.   If there are any validation errors, it can be obtained using  validationResult(req)  

To display only the first error at a time we add the following object to errors.array() 

Now handling the error part looks like this

So the final code looks like this

 

Testing Node.js,Express.js API with Mocha and Chai – Typescript

Contents >What is Mocha >what is Chai >what is Chai HTTP >Installing dependencies and getting started >Writing tests in the test files What is Mocha Mocha is a Javascript testing framework working on both Node.js and in the browser. We can use mocha to test APIs written to run in Node.js, created using frameworks like Express. Mocha runs the test cases serially and provides very accurate reporting. Mocha makes testing asynchronous testing easy and efficient. The latest version of Mocha available to use is 6.1.4. To install Mocha to be used with Node.js, use

Mocha is used in the development and testing phases and ideally not used in a production environment. So you use –save-dev while installing Mocha. What is Chai Chai is an assertion library used with testing frameworks like Mocha. An assertion in testing is an expression that will be true at a specific state of the application if there is no bug in the program. While testing Node.JS APIs, we can use this assertion library to check whether the response received from an API endpoint for a specific request is the expected one or not. To the latest version of Chai available to use is 4.2.0. To install…

Redis Tutorial Part 3 – Redis Data structures and working with Node.js ioredis

Redis Data structures Key-value stores mostly support string keys and string data but Redis does a lot more than that. Redis is not just a simple key-value string store It supports complex kinds of data structures, not just string. We will look more into this property of Redis in this tutorial and see how to utilize this using Node.js and ioredis module. Get the ioredis module installed on your app from https://www.npmjs.com/package/@types/ioredis   1 String – Basic kind of string. Lets us say the name of a person. We will see how we can store this value using ioredis We set value bar into key foo using set and get the value using get.

2 Binary Safe String – Can contain any type of data represented as a string: PNG images or serialized objects, for example. Here we have a base64 encoded data of an image.We store this data in redis.Remember a value can’t be bigger than 512 MB. base64 of png – iVBORw0KGgoAAAANSUhEUgAAACMAAAAjCAYAAAAe2bNZAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gUfFBM7nAl7igAAAPVJREFUWMNj1G/R/88wSAATwyACLMgcYzljojXefHmT4cvPLwzU1A93TJRpFEOZWxnRhj37+IzBa4oXA7n6b7y8wRAxJwK7Y3g5eBkYGBgYNl7ayPD843O8BmXYZjBI8UuhiMH0Ews0xDXwRxMDAwPDpoubGM4+OkvQMcM+AY86ZtQxo46hSXXAwMDA4Kfvx2AibzKwjvn84zMDAwMDg7+eP9HVATKA6SelOkEHjMhNCFJC5NmHZxgGUqqfcbQ9M9qeobQ9QyzA1Z4htj1EVHuGUkBJe2i0Ohh1zKhjRkZ7hlJASXuIhVrtEUrbQ6PtmdHcRA4AAAq6hb9r4YF9AAAAAElFTkSuQmCC

We can store buffer data as well in redis..

3 Lists – Collections of elements ordered according to the order of insertion

    4 Sets – Sets of data. Here we have a…

Redis Tutorial Part 2 – Redis Sentinel and master/slave usage with Node.js ioredis

Redis Sentinel  System designed to help manage Redis instances. As we discussed earlier, one Redis instance can be master and other instances can be slaves. The slaves can have exact data copies of the master server. The master will have replication ID. The biggest advantage of this architecture is that the slave can act as a master if the master fails. Redis Sentinel is the system that helps to make Redis instances with High Availability (HA) by managing failovers. Redis Sentinel Does the following jobs Monitoring – Checking if your master and slave instances are working as expected. Notification – Notifying something went wrong. May be via an API. Automatic failover – If a master is not working as expected, Sentinel can start a failover process where a slave is promoted to master     The configuration file for sentinel is sentinel.conf  redis-server /path/to/sentinel.conf –sentinel   In the sentinel.conf file, there is a line like sentinel monitor mymaster 127.0.0.1 6379 2 quorum – 2 This line determines which master the sentinel is going to monitor. The number 2 is called quorum. The number determines how many sentinels need to agree that the master is having a Failover so that the slave…

Understanding Promises in JavaScript : asynchronous behaviour of Javascript Part -2

In the previous article we learned about using callback for processing asynchronous requests.In ES06 Javascript introduced something called Promises which helps you deal with asynchronous operations in a better way The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. Promises provide a better way for managing asynchronous operations when compared to traditional callback-based way. Promises represent data that may not be available but will be available later upon completing some asynchronous operation.A promise has 3 states PENDING RESOLVED REJECTED Immediately that state of a Promise is pending.Resolved state means the asynchronous operation is fulfilled.Rejected means that the asynchronous operation was not completed and have some errors. Many Javascript native apis for asynchronous operations support promises since ES06 .Prior to that many libraries including JQuery provided us promises for doing asynchronous operations. Example for promises Javscript fetch operation returns a promise.

You can see that immediately the state of promise is pending.Now for resolving the promise and getting the output Promise.prototype.then() and Promise.prototype.catch() Promise.prototype.then() and Promise.prototype.catch() The promise object has a then method which returns the promise and a catch method which catches the error.See the following set of examples,first on promise…

Understanding Callbacks and Callback hell in JavaScript : asynchronous behaviour of Javascript Part -1

In  most programming languages , functions can accept other function(s) as arguments or return a function .Such functions are called Higher order functions. In JavaScript most APIs and Modules can accept function as an argument to a function .The functions are called  callbacks. Structure of callbacks

Note that JavaScript functions behave as objects.We can set a function as an object property or store a function into a variable. JavaScript is a non-blocking programming language.It doesn’t wait or block  an operation to finish but keeps on  executing.For example consider the case when data is fetched asynchronously,then javascript doesn’t wait for the asynchronous call to get data but  keeps executing the next line of code.So in order to do something with the data we can use callbacks.See the below example in which we use a setimeout to wait for the data just like an XHR request which may take some time to complete

Asynchronous callback with  Jquery and a callback function

  CALLBACK HELL Consider the above example in which we use a callback function which is passed as an argument to the $.get function in Jquery. Now what happens when we want to send subsequent requests is that the code becomes unreadable…

Sending email with SendGrid and Node.js – Using HTML templates:Step by step tutorial
Javascript and Node.js , Snippets / July 15, 2018

SendGrid is a communication platform that helps you manage communications with your clients via e-mail.SendGrid helps you manage email sending,design templates using code editor/design editor,run marketing campaign etc.To use send grid with your Node.js application,you need to integrate @sendgrid/mail package to your application.Follow the steps below to integrate and configure mail sending in Node.js with SendGrid   STEP 1 Create a SendGrid account using your email,provide the necessary information and confirm your account by clicking the confirmation mail from sendgrid   STEP 2 Sign in to your SendGrid account and go to dashboard.In the left side settings you will find an option called Api keys. Click on Api keys and generate a new api key for your sendgrid account.   STEP 3 – Integrating #sendgrid/mail To install sendgrid/mail for node run the following in the terminal.

In your node application,use the following code to import @sendgrid/mail

  STEP – 3 Creating a template in sendgrid To create aSendGrid template, go to the template section in the left side of your dashboard.Create a template  and then click the action button. From the action button choose the option New Version which will give you the following screen with design editor and code editor.Choose…

Understading working of javascript : Google’s JavaScript V8 Engine

What is javascript? Javascript is a single threaded,aynchrounous,non-blocking concurrent language.If you have an javascript code ,it is run by engines.Javascript v8 Engine powers Node.js ,Chrome browser,Electron(Desktop Application dev).There are many Javascript engines like Chakra(Microsoft), Spidermonkey(Firefox). We focus on V8 Javascript engine to understand more about JavaScript engines here.What V8 basically does is that it generate machine code from source code . All modern JavaScript engines use Just In Time(JIT) compilation also V8. V8 does’nt generate machine code Ahead of time but on run time when we need it.Compilation and execution goes at the same time. V8 features an interpreter called Ignition and an optimizing compiler  called TurboFan. Bookmark this page . Detailed study on V8 Engine will be available here soon…..  

HttpInterceptor in angular with example-Adding token to every request

HttpInterceptor –  feature in Angular 4.3. We may need to intercept Http request while building apps with Angular. Sometimes we may you need to intercept Http request to add something to request header or to do something with the response. We can use Http Interceptor to do some action when sending  a request.This can be achieved using  the following interceptor class which implemenets Httpinterceptor.The interceptor adds an ‘access_token’ and a  ‘token’ to the header.The tokens are stored in the local storage.To use HttpInterceptor we need to  implement HttpInterceptor in the following way

Import the interceptor the following way in module.ts files

  Modify and use the above class to implement Intercepror. For official documentation visit this page https://angular.io/api/common/http/HttpInterceptor

Share this page in social media platforms