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…

Set and Get Custom Response Header values using Angular 5 and Express.js – Node.JS

While working with Node.js and Angular, sometimes you might need to set some custom values in Response Header from the server-side and get these values in your Angular application. These values can be some tokens, keys or anything. This article is about completing this requirement. Server-side using Express.js and Node.js To set a custom value in the response header, you have to write the following code in your Express.JS server

Even if you set this token in the response header, to get this in your Angular application you need to allow these header values. The allowed default header values are Cache-Control Content-Language Content-Type Expires Last-Modified Pragma To allow your custom header value, you need to use the Cors module of Node.JS. To install the Cors module, use the following command.

Now the code to allow the customer header values with Cors module use the following code

Accessing the header values in your Angular 5 application   To get the header value in the application, you need to access the whole response object. For this, you need to add on observe: “response”  to the request options in the following way

When subscribing to the observable, you can get the…

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…

Filter array of objects having array of objects
Javascript , Requests , Typescript / March 20, 2019

Q: How to filter an array of objects having an array of objects Example object –

  A  –  When we consider the above object having an array of superheroes in members. Each superhero having an array of power. We need to get the superhero having the power 4/shield  in their power array, in this case We apply the filter function on the members array, then we apply filter function on powers array present in every item in the members array in the following way.

Gives output

On applying the filter function on inner powers array, if we get the length of the resulting array greater than 0, it means that the inner array contains the power4/shiled .  

logging in Node.JS – Express Application using Winston logger
Express.js , Javascript , Node.js , Typescript / February 20, 2019

Logging is keeping a record of all data input, errors, data output, and final results in a program. While developing an application, keeping track of responses, requests, errors, etc makes the development process more efficient. Keeping logs is also a part of code standardization. Logs can be displayed on the console and written to a file while working with Node.js.Here in this tutorial, we will learn how to create create a logger which keeps track of Request, Response, Errors and Time while building an ExpressJS application in Javascript/Typescript   Step 1 Install the Winston node package with the Node package manager

  Step 2 Create a logger.ts (.js file if you are working with  Javascript) preferably in a common folder outside, and add the following code to it  

In the above code, createLogger creates a new logger    

Adds Timestamp to your log. It defines formatting options  

Displays the log in console.  

Writes your error file to error.log and info to info.log    

If false, handled exceptions will not cause process.exit   Step 3 In your controller or where ever you want to create the log, import the logger file

Step 4…

Using Sequelize with typescript and express : Import all model files
Typescript , Uncategorized / February 17, 2019

STEP 1    Install Sequelize Install the latest version of Sequelize

Now create your migration script STEP 2  Initialize your project To create an empty project you  need to run init command

This will create seeders, config, migrations and models folders Modify the configuration file in your config folder accordingly   Step 3 Create your model and migration files

This will create Migration files in the migrations folder and model files in the models folder Step 4 Using models with typescript and express When you create multiple tables multiple model files will be created. To use all these model files at once, create a model folder in your project directory, create an index.ts file and include all the files using the fs module and path module of Node.js   The index.ts file will look like this  

The code

finds the model folder which is  outside your server files folder __dirname – Gives the current directory in which the executing file is located

Finds all .js model files inside the models folder

sequelizeconnection.import  import model files.In this case, it imports all model files

Above code adds the model to the model object

The…

Extend Express Request and Response : Typescript Declaration Merging
Typescript / February 12, 2019

When we use  TypeScript to Build a Node API with Express, you might need to add some additional properties to the Express request and response object. To add extra properties to the request and response object you need to extend the response and request interface. index.d.ts files are used to provide typescript type information about a module that’s written in JavaScript.For express, the index.d.ts is present inside the @types/express folder inside the node_modules folder.   As you can see in the index.d.ts file

The Request and Response extend core.Response and core.Request Extending Request and Response Object with Declaration Merging Declaration merging means that the compiler merges two separate declarations declared with the same name into a single definition. See below example in which the interface declarations are merged in typescript

So boy Object can have all the properties of both the interfaces. If the declaration was not merged adding property mark to the Object could have caused “property does not exist” error To achieve Declaration Merging with request and response interface follow these steps 1 Create a type.d.ts file in the root folder of the project and add the following code into it

2 Add the type.d.ts in the files of your tsconfig.json…

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