Categories
API Backend Developer Node

Top 10 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.

As a developer, one gets to smoothly use the same language for both clientside and serverside 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:

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
Hapi builds secure, powerful, scalable applications with minimal overhead and out-of-box functionality

Hapi is a configuration-driven pattern, traditionally modeled to control web server operations. A unique feature it has is the ability to create a server on a specific IP, with features like the ‘onPreHandler’, we can do something with a request before it is completed by intercepting it and doing some pre-processing on the request.

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
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.

Socket.io

Socket
Socket the fastest and reliable real-time engine

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.

Total.JS

Total.js is a modern and modular NodeJS supporting the MVC architecture. Angular.js, Polymer, Backbone.js, Bootstrap and other clientside 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
For fast, furious and powerful websites, REST services, real-time applications TotalJS is the best choice

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).

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.

Sail
Sail


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.

Derby

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

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 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.

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.

Meteor
Meteor

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.

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.

Loopback
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

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.

Koa
Next-generation web framework for NodeJS

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.

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).

NestJS
NestJS Framework- a progressive NodeJS Framework for building efficient, reliable and scalable server-side applications


Advantages of 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 going through this article, we can certainly understand that the adoption of a particular framework depends totally upon the kind of website and web application we are planning to build. The list is endless but we tried presenting 10 most useful NodeJS Frameworks for you depending on utilization and ubiquity in the javascript community

Categories
Angular Backend Developer Development Express Frontend Developers Node Programming

MEAN Stack Development Influences The Future Of Web Apps

The implementation and usage of Web app development is increasing and currently in a fast-moving realm. A highly competent architecture and navigation are in demand in today’s web applications. They need to be dynamic, user-friendly, robust, and flexible. With the developments and evolutions in technology leaves web developers with many choices for their app. One essential factor while choosing a suitable framework for the solution, it is essential to determine a software technology that combines the best features to work.

MEAN stack is a growing contemporary trend for JavaScript development. This stack is the one technology that meets all the requirements for a fully efficient development in the best possible way. An open-source JavaScript bundle for web apps, MEAN is an acronym that stands for:

  • M stands for MongoDB,
  • E stands for Express,
  • A for AngularJS and
  • N for NodeJS.
mean stack development
Mean Stack Development

Web developers find MEAN stack application development as an attractive choice and are switching to it as it is on the latest technology-go-to basis, the full-stack JavaScript. The flawless combination of these 4 robust technologies makes it the most sought out bundle for web app development services.

What makes this stack an ideal choice for developing a website is as follows:

  • Flexible in developing for any size and type of organization.
  • Best viable technology solutions for all Business segments from startups, SMEs, or large enterprises.
  • Straightforward for frontend and backend developers to apply this framework.
  • Suitable framework for any multi-layer application.
  • Immense benefit in terms of productivity and performance.

Knowledge of JavaScript language mechanisms from the presentation layer to the database is all you need to proceed with the MEAN stack software.

A brief look into the 4 Components of MEAN

MongoDB is the open-source, NoSQL database framework for JavaScript

  • Cross-platform document-oriented database model
  • A schema-less, independent NoSQL database
  • With JavaScript, it limits to a single language for the complete application development
  • Collects and stores the application’s database in MEAN
  • High scalability in both storage and performance
  • Cost-effective and useful in transferring both client and server-side data without compromising data access
  • Expandable resources, load balancing and handling increased activity durations

ExpressJS is the lightweight server-side JavaScript framework

  • Web application framework for NodeJS and simplifies the development process
  • Cuts down the entire process of writing secure code for web and mobile applications
  • Developers can include New features and enhancements
  • Minimal structure mainly used for backend development and aids decluttering
  • Building smooth server-side software with NodeJS
  • Prevents accidental redefinition of a variable, therefore, eliminating errors and time-saving

AngularJS is the web frontend JavaScript framework

  • A browser-free MVC JavaScript UI framework with data binding
  • Popular Google’s front end framework that enables smooth flow of information throughout the application
  • Enables rapid development of dynamic single-page web apps (SPA’s)
  • Modular structure and develops for both mobile and web
  • Easy-to-use templates and high scalability for full stack front end augmentation

NodeJS is the open-source JavaScript-based runtime framework

  • Built on Chrome’s JSV8 engine
  • Before execution, compiling JavaScript source code to native machine code is done
  • Helps build scalable, secure web applications and comes with an integrated web server
  • Maintains a vast ecosystem of open source libraries and components
  • Quickly responds to usage spikes during runtime

The reasons behind why the preference for this Stack Development software for Web Applications are as follows

  • Inexpensive in Nature

Due to its budget-friendly nature, development finds its main reason to be a cut above other technology frameworks in existence. Also, as it is a full-stack development, unnecessary expenditure over resources can be eliminated for the customers as well as the developers. Hence, a large volume of reusability and sharing of code amongst the developers occurs. This process, thereby, restrains the budget considerably.

  • Full JavaScript Framework

Since the framework is entirely JavaScript, it has its set of benefits to provide in terms of exceptional user experience and data handling. Both Linux, as well as Windows OS, are supported. Data recovery is speedy due to the power and dependability of the framework. Seeing that both NodeJS and AngularJS contribute to a better condition to build competent web apps and more traffic occurrences.

  • Universal Accessibility to JSON

It adds to the advantage of having a seamless expanse of data within layers because JSON is present all over, whether it’s AngularJS, MongoDB, NodeJS, or ExpressJS. The highlight is that rewriting the code is not necessarily required. Data flow between the layers is much more comfortable and not necessary to be reformatted. MEAN utilizes a standard JSON format without exception for data. Also, it becomes increasingly simpler while functioning with APIs.

  • Highly Scalable and so very Popular

Full-stack development with MEAN is scalable, and its ability to handle multiple users makes it a reliable choice and a business favorite. In addition to that, all four components are open source. The development time is also faster, owing to the presence of various frameworks, libraries, and reusable modules. Because of its swiftness in operation, easy to collaborate, easy to learn, and takes less time to develop cloud-native applications, it’s eventually a developer’s choice.

Being an open-source makes it available for free. MEAN can be easily deployed as it includes its web server. The development potential is on the higher side for many other JavaScript resources with this stack technology. Because of this, MEAN stack web development has made avid developers look ahead to work, and the built-in elements of JavaScript make it even more, easier to utilize resources in this sector.

  • Reusability and Fixing is much simpler

Streamlining the development process by using a single language across the whole application is possible. Thus it becomes easy for developers as it eliminates the need for different specialists for developing each part of any web application. It also enables easy tracking of the entire development flow, monitor data exchange, and catch sight of errors/bugs. This technology can be even more improvised with the help of a few third-party opensource tools and libraries that allow the frontend and the backend to reprocess quickly.

  • Lowered Development Expenses

A MEAN application penetrates the tech-world improvised to take advantage of all the cost savings and performance improvements of the cloud. The primary feature of this innovative technology is that it does not incur any needless expenses, thereby a large volume of concurrent users can be reached. Code reuse across the entire application reduces reinvention, and code sharing helps developers to reach their target objective within the committed time frame and allocated budget.

  • Enables Collaboration Between Developers

The stack technology has a lot of community support behind, and finding answers to questions or even hiring assistance can be obtained. All developers speak the same programming fundamentals, and so it’s effortless and efficient for them to understand the nuances of web app development mutually. The advantage of hiring MEAN stack developers is more since they can effectively understand, facilitate association, and manage the project with ease.

  • Access to Congruent Coding

MEAN stack helps to transfer within frames, i.e., the server-side and the client-side. Creating code in one framework and transferring to another is achievable without any difficulty or disruption in performance. It is yet another critical feature of this technology in comparison to the rest.

  • Systematic & Exceptionally Flexible

It is incredibly swift to prototype because the stack has its internal web server that enables opening without difficulty, and the database can be systemized on-demand to contain momentary usage spikes. Consistent language and flexibility give it an added competitive edge for developers.

Some of the famous and familiar websites that use MEAN stack are Netflix, Uber, LinkedIn, Walmart, PayPal, and Yahoo. The web development frameworks and databases are enhancing every day. This is the most suitable stack technology for cutting-edge web and mobile applications development.

Categories
Node

Hire Node.js Developers

Node.js is rapidly and widely taking over as the go-to technology by the developers across the globe in building various Projects in Web Application framework, Social media apps, Real-time tracking apps, Video and text chat engines, Online games, Collaboration tools, and Backend static file server, etc. Evidently, Node.js is gaining prominence amongst big techno giants and they are actively on the lookout to hire Node.js developers to like never before because of the ease it offers in building fast and scalable network applications.

Node JS Image

Node is neither a Programming language nor a framework, it is a single-thread, single-process system ensuring shared-nothing design along with OS (Operating System) process boundaries.

What is Node.js

Node.js was introduced by Ryan Dahl back in 2009, Dahl criticized the restricted possibilities of ‘Apache HTTP Server’ in handling a lot of concurrent connections and code creating a procedure (sequential programming), where code blocked the entire process or multiple execution stacks in case of the simultaneous connections.

Hire node js developer

It is a run-time environment that is built on Chrome’s V8 JavaScript engine where the user gets the flexibility to work on both the client and the server-side as well. Node.js is an open-source framework that runs on popular OS platforms like Linux, Mac OS X, and Windows.

Node is best suited for data-intensive, real-time applications that run across distributed devices as it is an asynchronous event-driven, non-blocking I/O model (lightweight and efficient for such intense applications).

 Safety advantages:

  • Good Performance
  •  Coupling in client and server
  •   Hosting service
  •  Cloud-enabled
  •  Lightweight Node.js services
  •  Supports quick native binding
  •   Minimum viable product (MVP) delivery
  •  Easy to use, open-source packages and modules
  •  Ease of execution & installation
  •  Supports multiple-platform

Node.js is the biggest open-source platform fetching more than 15 million downloads every month, receiving a billion package requests every week. SimilarTech reports suggest web development firms from the United States of America are leading the race in hiring Node.js developers followed by Russia to hire Node.js developers for their major business projects.

benefits of node

 Dictionary.com, Flickr.com, Healthline.com, and Thesaurus.com are a perfect example of Node.JS‘s prowess in providing an efficient and lightweight platform.

Why Node For Your Projects

  • Best Suited For Real-Time Web Applications

Real-time web applications transmit instantaneous information between the user and the server. And Node provides many impressive backend solutions than any other technology for a web application, allowing a quicker and swift exchange of data between the client and the data server. It provides direct communication with web sockets and many other real-time protocols as a backend solution.

Hire Node.js developers

A growing need for real-time communication for various projects in businesses is making Node.js a widely accepted technology. It provides a steady, continuous connection between a browser and a server and transmits immediate information which shows up instantly.

  • Fast And Easy Suite

Node.js is faster as compared to GO, PHP and Java because of the V8 engine which can handle concurrent requests. V8 engine compiles functions written in Javascripts to machine code at a tremendously fast and impressive rate. Node.js development is faster in processing requests and avoids delays because of its Non-blocking Input/ Output model which is asynchronous in request handling.

Reasons to hire node developer
REASONS TO HIRE NODE DEVELOPERS

For example, Linkedin the biggest social, networking platform moved from “Ruby on Rails to Node.js” last year to combat mobile app’s backend solutions. This shift on Node.js has made the application faster than the previous one and much lighter in weight.

  •  Competent Productivity Standards

The single-threaded, event-driven architecture of Node.js allows it to handle multiple concurrent connections efficiently using RAM for processing during the whole time.

node js stats

Node.js is written in C++, built for operating multiple systems at super fast speed. Both V8 and Node comes with optimized performance, security patches, support for modern Javascript features and regular updates ensuring better productivity. Also, in Node.js transforming JSON data occurs quickly by default. Robust tools like the PM2 process manager make Node.js easier to monitor, optimize and deploy applications.

  •  Cross-platform

Our developers have been very impressed with all the specialty features that Node.js is bringing to the table and highly innovative enterprises understand that Node.js is presently the best option possible for better performance and code efficiency.

node js survey for business

Platforms like Electron and NW.JS let the developers build cross-platform desktop apps with Node.js which means you can use some of the code from the web application in its desktop versions for macOS, Linux, and Windows.

  • High-End Solution To Data Queries

The database queries like MongoDB, NoSQL databases, CouchDB get easy high-end solutions in Node JS development.

Nodejs Server architecture

Also, there is no need to modulate syntax differences in Node.js and NoSQL databases.

  • Dynamic Package Manager (NPK)

Package Manager‘ was introduced in January 2010, making it easy to publish and share the source code of Node.js libraries. Additionally, this design offers simple installation, uninstallation, and updating libraries.

Node comparision with other languages

NPM Enterprise allows you to run NPM’s infrastructure behind an organization’s firewall which provides businesses access to a private registry with advanced security features to help them control intrusion to code, identification of vulnerabilities if any, and automatic replacement of unsafe code.

NPM provides numerous libraries and reusable templates to incorporate in the code to fetch more value with minimum effort and time.

  • Easy Coding

Node provides ease of learning which makes it easier for web developers to code easily in JavaScript from both the server and client-side.

  • Best Remedy For Proxy Servers

Node.JS infrastructure offers the best solution for the proxy server. Suppose, if there is a server-side application dealing with third-party links that collect data, save videos and images from various sources, then Node.js act as a Proxy for that organization that does not have appropriate infrastructure for proxy needs.

nodejs for api

Few Examples Of Top Applications Built On Node.js:

  • Netflix
  • Trello
  • Walmart
  • LinkedIn
  • Medium
  • Nasa
  • Groupon
  • eBay
  • Uber
  • Yahoo
  • Homemade
  • Paypal
  • GoDaddy

Cons:

The biggest disadvantage working on Node.js is its inefficiency to process CPU bound tasks as when a heavy request comes to the event loop, Node.js set all the CPU available to process it first then answer other queued requests. Hence, Node.js is not recommended for heavy computations as it results in slow processing and overall delay in the event loop.

node drawbacks

Although multithreading is introduced as an experimental feature with a 10.5 update version called worker threads module which is used to leverage additional threads from a thread pool, to carry CPU bound tasks. But this too comes with the limitation of working on machines with multiple cores as Node.js allows one core per thread.

Concluding Note:

Node.js as server technology provides a great boost by using the same language for both the front-end and back-end. It provides an efficient, cross-functional application saving a lot of development costs and increasing profitability. Node.js ensures great speed and performance for real-time web applications. Node.js community is constantly growing and the knowledge base for the technology is widely and easily available. Also, Node.js technology stack is open-source and free.

Node.js is great for applications requiring immediate updates, like for collaboration tools and online documentation suites. Node.js is perfect for data streaming applications, like Netflix is a perfect example displaying Node’s powerful data streaming capabilities. NodeJS is very useful in sending large amounts of data in smaller packages instead of a single batch.

Overall it’s a great open-source platform that allows easy creation of web servers and networking tools using Javascript and a collection of “modules” that handle various core functionalities with greater ease of use and better productivity for your projects.


Categories
Backend Developer Database Javascript Node

25 Interview Questions on Node.js

Here we listed down the most asked interview questions on Node js so that you don’t have to go anywhere. This is a one-stop destination for all your queries. We provide you the top 25 interview questions on Node js so you can ace your interview. Let’s just look at the questions below.

1. What is Node js?

The first and most asked question is what is Node js?. Node js is an open-source server environment that uses javascript to make web software that is computationally simple but is easily accessed. It works really fast and can run on different platforms like Windows, Linux, Mac OsX, etc

2. What are some key benefits to Nodejs?

There are numerous benefits of Node js which are explained as follows.

  1. It is fast because it is built on Google chrome’s V8 JavaScript engine which makes it really fast.
  2. Node js has no buffering and no blocking while working. It output the data in chunks.
  3. It is Asynchronous meaning Nodejs never stops for an API to return the data. It is ready to take the next request.

3. Is Node js single-threaded? If yes, then why?

Well yes and actually no. NodeJS is single-threaded since no two functions can be run at the same time. Although, a running program called a process can have multiple threads. NodeJS runs only one program at a time to implement its asynchronous nature of program execution hence a single-threaded server environment but can a program can use multiple threads internally to yield optimal performance hence a multi-threaded server environment.

4. What type of applications you can build using Node js?

  • Streaming apps
  • Chat applications
  • Internet of things
  • Microservices
  • Collaboration tools
  • You just name it and we can build it using Node.js

5. How the content of a file is read by Node js?

The NodeJS’s fs (file-system) module provides an API to interact with the system files. The files can be read with multiple methods available to us. In the example below, we will be using the readfile method of fs module to read the contents of a file.

var fs = require(‘fs’);

fs.readFile(‘DATA’, ‘utf8’, function(err, contents) {

    console.log(contents);

});

console.log(‘after calling readFile’);

if you want to know in synchronous manner then have a look in this sample

var fs = require(‘fs’);

var contents = fs.readFileSync(‘DATA’, ‘utf8’);

console.log(contents);

 

6. Discuss the streams in Nodejs? And what are the different types of streams?

Streams are something that allows the reading and writing of data from source to destination in a continuous process.

Streams are of 4 types

·         <Readable> that promotes reading operation

·         <Writable> that promotes writing operation

·         <Duplex> that promotes above both

·         < Transform> is a kind of duplex stream which does the computation based on available input.

7. What is closure?

A closure is a function that is sustained in another scope that has access to all other variables in the outer scope.

8. Does Zlib use in Nodejs? If yes, then why?

Yes, Zlib used in Nodejs and Zlib was written by Jean-loup Gailly and Mark Adler. It is a cross-platform data compression library. You need to install a node- Zlib package in order to use Zlib in Nodejs. A sample is given below which shows the code to use Zlib. 

var Buffer = require(‘buffer’).Buffer;

var zlib = require(‘zlib’);

var input = new Buffer(‘lorem ipsum dolor sit amet’);

var compressed = zlib.deflate(input);

var output = zlib.inflate(compressed);

9. Discuss the globals in Node.js?

Globals basically comprise three words which are Global, Process and Buffer. Let’s discuss it one by one.

Global–  As the name is suggesting Global is something which has many things under its umbrella. So it’s a namespace object and act as an umbrella for all other objects < global>

 Process– It is a specified type of Global and can convert Asynchronous function into an Async callback. It can be linked from anywhere in the code and it basically gives back the information about the application.

 Buffer– Buffer is something that is known as a class in Nodejs to tackle the binary data.

 

10. Differentiate between Nodejs and Ajax?

Ajax is used on a specific section of a page’s content and update that specific portion rather than updating the full part of the content.

Nodejs, on the other hand, used for developing client-server applications. Both of the above serve different purposes and these are the upgraded implementation of JavaScript.

11. What is Modulus in Node Js?

Modules are a reusable block of code whose existence doesn’t impact alternative code in any means. it’s not supported by Javascript. Modules come in ES6. Modules are necessary for Maintainability, Reusability, and Namespacing of Code.

12. What do you mean by an event loop and how does it work?

An event loop tackles all the callbacks in any application. It is the vital component of Nodejs and the main reason behind the non- blocking I/O. Since Node.js is associate event-driven language, you’ll be able to simply attach an observer to an occurrence so once the event happens the callback is executed by the precise observer.

13. What is callback hell?

Callback Hell is additionally referred to as the Pyramid of Doom. it’s a pattern caused by intensively nested callbacks that square measure unreadable and unwieldy. It usually contains multiple nested request functions that successively build the code exhausting to browse and correct. it’s caused by improper implementation of the asynchronous logic.

query(“SELECT clientId FROM clients WHERE clientName=’picanteverde’;”, function(id){

  query(“SELECT * FROM transactions WHERE clientId=” + id, function(transactions){

    transactions.each(function(transac){

      query(“UPDATE transactions SET value = ” + (transac.value*0.1) + ” WHERE id=” + transac.id, function(error){

        if(!error){

          console.log(“success!!”);

        }else{

          console.log(“error”);

        }

      });

    });

  });

});

14. What are the types of API functions in Nodejs?

There are mainly two types of API functions, one is blocking function and the other is non- blocking function.

Blocking function:  These functions implement synchronously and all other code is blocked from implementing until an I/O event that is being waited occurs.

For instance

const fs = require(‘fs’);

const data = fs.readFileSync(‘/file.md’); // blocks here until file is read

console.log(data);

// moreWork(); will run after console.log

Non-blocking Functions: These functions implement ASynchronoulsy and in this multiple, I/O calls can be executed without being waited for.

For instance

const fs = require(‘fs’);

fs.readFile(‘/file.md’, (err, data) => {

  if (err) throw err;

  console.log(data);

});

// moreWork(); will run before console.log

Since fs.readFile () is non-blocking, moreWork () does not have to wait for the file read to complete before being called. This allows for higher throughput.

15. What is Chaining in Nodejs?

Chaining is a system where one stream has an output and that is connected with the output of another stream that creates a chain-like formation of multiple stream operations.

16. Explain the Exit codes in Nodejs? Name some of the exit codes?

As the name is suggesting exit codes are those codes that are used to end the Process where process means a global object that represents a node process.

There are some exit codes given below.

  • Fatal error
  • Uncaught fatal Exception
  • Internal javascript Evaluation failure
  • Non-function internal exception handler
  • Unused
  • Internal exception handler Run-time Failure.

17. What is the working of control flow function?

Control flow function in Nodejs is a code that is implemented between Asynchronous function calls. There are some steps given below which must be followed while implementing it.

  • First, the order of execution must be controlled
  • Second,  collection of the required data is must,
  • Third, concurrency must be limited.
  • When the above process is done the next step of the program is requested.

18. Differentiate between readfile and createReadSTream in Nodejs?

  • Readfile loads complete file that you have marked to read on the other hand createReadStream reads the complete file in the pieces you have declared.
  • CreateReadStream works faster than Readfile. The client will get slower data in the latter one.
  • In Createreadstream, it first read by memory in parts the client will get a part of data that is read and this process will continue until it finishes but in Readfile a file is read by memory completely then the client will get it.

19. How to update a new version of NPM in Nodejs?

For this, you have to give a command for updating in Nodejs

$ sudo npm install npm -g

/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js

npm@2.7.1 /usr/lib/node_modules/npm

20. How to prevent/ fix callback hell?

There are three ways to prevent fix callback hell

Handle every single error

Keep your code shallow

Modularize – split the callbacks into smaller, independent functions that can be called with some parameters then joining them to achieve desired results.

The first level of improving the code above might be:

var logError = function(error){

    if(!error){

      console.log(“success!!”);

    }else{

      console.log(“error”);

    }

  },

  updateTransaction = function(t){

    query(“UPDATE transactions SET value = ” + (t.value*0.1) + ” WHERE id=” + t.id, logError);

  },

  handleTransactions = function(transactions){

    transactions.each(updateTransaction);

  },

  handleClient = function(id){

    query(“SELECT * FROM transactions WHERE clientId=” + id, handleTransactions);

  };

query(“SELECT clientId FROM clients WHERE clientName=’picanteverde’;”,handleClient);

You can also use Promises, Generators and Async functions to fix callback hell.

21. What is the procedure to handle child threads in Nodejs ?

In general, Node.js could be a single-threaded method and doesn’t expose the child threads or thread management ways. however, you’ll still build use of the child threads victimization spawn() for a few specific asynchronous I/O tasks that execute within the background and don’t sometimes execute any JS code or hinder with the most event loop within the application.

22. What are the different timing features of Nodejs?

Node.js gives a Timers module that contains different functions for executing the code after a stipulated period of time. There are some features of different timing that are given below.

setTimeout/clearTimeout –  It is Used to schedule code execution after a specific amount of milliseconds

setInterval/clearInterval – Used to implement a block of code multiple times

setImmediate/clear Immediate – Used to implement code at the end of the current event loop cycle

process.nextTick – Used to schedule a callback function that needs to be requested in the next repetition of the Event Loop.

23. What is the usage of buffer class in Nodejs?

Buffer category in Node.js is employed for storing the raw information similar manner of an array of integers. However, it corresponds to a raw memory allocation that’s settled outside the V8 heap. it’s a worldwide category that’s simply accessible will be accessed in AN application while not importation a buffer module. Buffer category is employed as a result of pure JavaScript isn’t compatible with binary knowledge.

24. What is the role of REPL in Nodejs?

REPL stands for Read, Eval, Print, Loop. The REPL in Node.js is used to implement ad-hoc Javascript statements. The REPL shell allows entry to javascript directly into a shell prompt and evaluates the results. For the purpose of testing, debugging, or experimenting, REPL is very critical.

25. What is libuv in Nodejs

libuv is a Cross-platform I/O abstraction library that supports asynchronous I/O based on event loop. It is written in C and released under MIT Licence.

libuv support Windows IOCP, epoll(4), kqueue(2), and Solaris event ports. Initially, it was designed for Node.js but after that, it is also used by other software projects.

Categories
Angular Development Frontend Developers Javascript Node React Developers ReactJS

23 JavaScript Interview Questions And Answers

JavaScript is a high-level, dynamic, untyped, and interpreted programming language. It has been standardized in the ECMAScript language specification. Alongside HTML and CSS, it is one of the three essential technologies of World Wide Web content production; the majority of websites employ it and it is supported by all modern web browsers without plug-ins or any kind of other extensions.

“Javascript is the duct tape of the Internet.”

Let’s starts with some common Qs about JavaScript.

  • JavaScript is developed by- Netscape Communications Corporation Mozilla Foundation, Ecma International.

  • It designed by- Brendan Eich

  • JavaScript is called- JS

  • The extension filename of JavaScript- .js

  • JavaScript Media type- application/javascript, text/javascript.

  • The current version of JavaScript- ECMAScript 2018.

In this guide, you’ll find example interview Qs and answers you can refer to when seeking a new JavaScript developer to make your dynamic user interfaces come to life. You’ll also get some practical Qs on how to use these Qs to reliably identify results.

Q 1. Is JavaScript and JScript the same?


Answer. Both JavaScript vs JScript is designed to make dynamic web pages and interactive content.

  • Javascript is a scripting language (supports scripts) for Web pages but it is also used in non-browser environments as well. It is a powerful, lightweight, interpreted, scripting language with first-class functions (i.e. the language supports passing functions as arguments to other functions).
  • JScript is also a scripting language, much similar to JavaScript. It is a dialect of the popular ECMAScript standard reverse-engineered by Microsoft. JScript is subsidy by Microsoft and used in one of the most popular web browsers Microsoft’s Internet Explorer. JScript can also be called “Microsoft’s JavaScript”.
DifferenceJavaScriptJscript
TypeScripting languageScripting language owned by Microsoft.
SimplicityIt needs to write scripts manually. Same as JavaScript in this context.
Browser
Compatibility
It needs to handle multiple
browsers compatibility.
Only support by Microsoft’s internet
explorer.
Active Content
Creation
Does not support active content
creation.
With JScript, you can create active
online content for WWW.
Object
Access
JavaScript cannot access web browser
objects.
JScript can easily access-
objects exposed by internet explorer.

Q 2. Justify the use of let and const in JavaScript?


Answer. Earlier in javascript, developers use the var keyword for creating variables. let & const keyword is introduced in version ES6 with the vision of creating two different types of variables in javascript one is immutable and the other is mutable. The use if let and const in JavaScript:

  • let

let is used for variable declaration as it comes as an improvement to the var declarations. let is a block code bounded as {}. So a variable declared in a block with the let is only available for use within that block.

  • Example:
let greeting = "say Hi";
   let times = 4;

   if (times > 3) {
        let hello = "say Hello instead";
        console.log(hello);//"say Hello instead"
    }
   console.log(hello) // hello is not defined
  • const

Variables declared with the const maintain constant values. const declarations share some similarities with let declarations.

Like let declarations, const declarations can only be accessed within the block it was declared in.

const cannot be updated or re-declared

This means that the value of a variable declared with const remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with const.

  • Example:
const greeting = "say Hi";
    greeting = "say Hello instead";//error : Assignment to constant variable. 

Q 3. Explain the MUL function in JavaScript?


Answer. MUL means a simple multiplication of numbers. It is a technique in which you pass one value as an argument in a function and that function returns another function to which you pass the second value and the process goes on. Multiplies two expressions. This is the functional equivalent of the (*) operator.

Q 4. List the Frameworks and Data types supported by JavaScript?


Answer. The frameworks used by JavaScript are:

  • Node.js
  • Angular.js
  • React
  • Vue.js
  • Ember.js
  • Meteor
  • Backbone.js

Data types supported by JavaScript are:

  • Symbol
  • String
  • Boolean
  • Null
  • Undefined
  • Number
  • Object

Q 5. How you can redirect a page to another page in JavaScript?


Answer. There are several ways to redirect the page to another page in JavaScript. These are:

  • Using location.href: It is the first approach to redirect page. In this, we can go back to access the original document.

  • Using location.replace: Another approach to redirect page. In this, it is not possible to navigate back to the original document by clicking on the back button as it removes the URL of the original document. 

Q 6. Clarify some design patterns in JavaScript?


Answer. The design pattern is a reusable solution to a commonly occurring problem in software design. Some of the design patterns are:

  1. Behavioral Patterns: 
    These patterns are to improve communication between objects and to recognize patterns. Visitor, states, strategy, Memento, Mediator, Iterator, Command, Chain of responsibility and observer are examples of Behavioral patterns.

  2. Creational design pattern: 
    These patterns deal with the mechanism of object creation which optimizes object creation with the basic approach. Factory method, Abstract Factory, Builder, Prototype, and Singleton are the categories of Creational design pattern.

  3. Concurrency design patterns: 
    These patterns handle with multi-thread programming paradigms. Some popular categories of concurrency design patterns are Scheduler, Nuclear reaction, and Active object.

  4. Structural design pattern: 
    These patterns deal with different classes and objects to provide new functionality. Adapter, Bridge, Composite, Decorator, Facade, Flyweight, and proxy are the categories od structural design patterns.

  5. Architectural design patterns: 
    These patterns used to deal with architectural designs. Like: MVC (Model-View-Controller), MVVM (Model-View-ViewModel), and MVP (Model-View-presenter).

Q 7. Explain promise in JavaScript?


Answer. A Promise is a proxy for a value not necessarily known when the promise is created. It allows the developers to associate handlers with asynchronous action’s eventual success value or failure reason. Essentially, a promise is a returned object that you can attach callbacks to, instead of passing callbacks into a function.

  • 3 states to a promise:
  1. pending: awaiting promise response.
  2. resolve : promise has successfully returned.
  3. reject: failure occurred.
  • Syntax:
new Promise(executor);
Function process of promise

Q 8. What are the advantages of using JavaScript?


Answer. Some key advantages of JavaScript are:

  • JavaScript is an easy language to learn.

  • It is comparatively fast for the end-user.

  • Easy to debug and test.

  • JavaScript is platform-independent.

  • It works on the client6-side.

  • Also, has powerful frameworks.

  • Event-based programming language.

  • Procedural programming capabilities.

Q 9. How to get inner HTML of an element in JavaScript?


Answer. InnerHTML property of HTML DOM is used to get inner Html of an element in JavaScript.

  • Example:
<script type="text/javascript">
	var  inner= document.getElementById("inner").innerHTML ;
	console.log(inner); // This is inner Element
	document.getElementById("inner").innerHTML = "Html changed!";
	var  inner= document.getElementById("inner").innerHTML ;
	console.log(inner); // Html changed!
</script>

Q 10. What are the Arrow functions in JavaScript?


Answer. Arrow functions were introduced in ES6. Arrow functions allow the developers to write shorter function syntax.

hello = () => {
  return "Hello World!";
}

An arrow function expressions is a syntactically compact alternative to a regular function expression, but this function has its own bindings to the arguments, super, this, and new.target keywords.

Q 11. How to encode and decode a URL in JavaScript?


Answer. Encode and Decode a URL in JavaScript:

  • encodeURI() function is used to encode an URL in Javascript.It takes a url string as parameter and return encoded string. Note: encodeURI() did not encode characters like / ? : @ & = + $ #, if you have to encode these characters too please use encodeURIComponent().

    Usage:
var uri = "my profile.php?name=alex&occupation=danciNG";
var encoded_uri = encodeURI(uri);
  • decodeURI() function is used to decode a URL in Javascript. It takes an encoded URL string as a parameter and returns decoded string.

    Usage:
var uri = "my profile.php?name=alex&occupation=danciNG";
var encoded_uri = encodeURI(uri);
decodeURI(encoded_uri);

Q 12. Classify the different ways of empty an array in javascript?


Answer. In Javascript, there are many ways to empty an array, here are the four major ways to empty an array:

  • By poping the elements of the array.
var arr2 =[1,4,5,6];
while(arr.length > 0) {
    arr.pop();
}
  • Assigning array length to 0.
var arr2 =[1,4,5,6];
arr2.length=0;
  • Using .splice().
var arr =[1,4,5,6];
arr.splice(0,arr.length)
  • By assigning an empty array.
var arr1 =[1,4,5,6];
arr1=[];

Q 13. How to remove duplicates from JavaScript Array?


Answer. The three main approaches to remove duplicates from JavaScript Array:

  • By using Set:

It is the simplest way to remove duplicates because Set is an inbuilt object to store unique values in an array.

How to use set:

 function uniquearray(array) { 
       let unique_array= Array.from(set(array)) 
       return unique_array;}

By this code, you can easily create a set of an array that automatically eliminates duplicate values in JavaScript.

  • By using Filter:

This is another way to remove duplicates from an array. In the Filter method, it requires three arguments: Current element, Index of the current element, and Array.

How to use Filter:

function unque_array (arr){
 let unique_array = arr.filter(function(elem, index, self) {
 return index == self.indexOf(elem); } 
return unique_array }
 console.log(unique_array(array_with_duplicates));
  • By using for loop:

This is also a way to remove duplicates, but in this developer make an empty array in which those elements will be added from the duplicate array to get the unique elements.

Code use as:

Array dups_names = ['Tom', 'Pal', 'Fred', 'Rongo', 'Ron'];
function dups_array(dups_names) {
 let unique = {};
 names.forEach(function(i) {
    If (!unique[i]) {
      unique[i] = true;    }
  });
return Object.keys(unique);}   // Tom, Pal, Fred, Rongo
Dups_array(names);

Q 14. Are the results of 6 + 4 + ‘45’ and 6 + 4 + 45 the same?


Answer. No, the results should be different from each other because the results for the two statements are very different from each other. 6 + 4 + 45 gives the result 55, which is the expected answer for the addition of numbers. But, 6 + 4 + ‘45’ returns 1045 as a result. This is because 45 is a string and 6 and 4 are numbers. The presence of the string specifies that the + operator is a string operator for concatenation rather than an arithmetic operator.

Q 15. What is null, undefined, and undeclared JavaScript variable?


Answer.

  • Null

It can be assigned to a variable to represent no value. It is an assignment value.

var b = null;
console.log(b); //null
console.log(typeof b); //object
  • Undefined

It means a variable has been declared but has not yet been assigned a value

var a;
console.log(a); //undefined
console.log(typeof a); // undefined
  • Undeclared

If a variable is not declared then the browser throws an error.

console.log(nonDeclaredVariable);
 
// Uncaught ReferenceError: nonDeclaredVariable is not defined
//    at <anonymous>:1:13
 
console.log(typeof nonDeclaredVariable); //undefined

Q 16. What is the purpose of ‘This’ operator in JavaScript?


Answer. The JavaScript this keyword refers to the object it belongs to. This has different values depending on where it is used. In a method, this refers to the owner object and in a function, this refers to the global object.

Q17. Explain the terms synchronous and asynchronous code.


Answer. The synchronous code is something that should be finished before anything else can happen, or in other words, the synchronous code is blocking. And the Asynchronous code is something in which actions can happen and is not dependent on other actions- in other words, it is non-blocking.

Q 18. Are “==” and “===” operators different in JavaScript?


Answer. “==” checks only for equality in value whereas “===” is a stricter equality test and returns false if either the value or the type of the two variables are different. So, the second option needs both the value and the type to be the same for the operands.

Q 19. How to Calculating the Fibonacci series in JavaScript?


Answer. Fibonacci Series is a sequence of numbers where the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two.

function fibonacci(n) {
let arr= new Array(n+1);
arr[1]=1;
arr[2]=1;
for(let i=3;i<=n;i++)
{
 arr[i]=arr[i-1]+arr[i-2];
}
for(let i=1;i<=n;i++)
{
 console.log(arr[i]);
}
return;
} 


Answer. The process of Create, Read, and Delete a cookie by using JavaScript:

  • Cookie creating process-

The simple way to create a cookie is to assign a string value to the document.cookie object.

Syntax:

document.cookie = "key1 = value1; key2 = value2; expires = date";
  • Reading a cookie-

It is just as simple as writing one for the developers because of the value document.cookie object is the cookie. So you can use this string whenever you want to access it.

This fulfills your two conditions:

  1. The document.cookie string will keep a list of anme= value pairs separated by semicolons.

  2. It is easy for the developers to use the string’s split() function to break the string into key and values.
  • Delete a cookie-

If you want to delete a cookie, that subsequent attempts to read the cookie return nothing, you just need to set the expiration date to a time in the past. You should define the cookie path to ensure that you delete the right cookie. Some browsers will not let you delete a cookie if you don’t specify the path.

Q 21. Consider the following code:

function test() {
console.log(a);
console.log(foo());
var a = 1;
function foo() {
return 2;
}
}
test();

What is the result of executing this code and why?

Answer. The result of this code is undefined and 2.

The reason is that both variables and functions are hoisted but variables don’t retain any assigned value. So, at the time the variable “a” is printed, it exists in the function but it’s still undefined. Stated in other words, the code above is equivalent to the following:

function test() {
var a;
function foo() {
return 2;
}
console.log(a);
console.log(foo());
a = 1;
}
test();

Q 22. List the comparison operators supported by JavaScript?


Answer. The comparison operators are:

  • < Less than
  • > Greater than
  • <= less than or equal to
  • >= Greater than or equal to
  • == Equal to
  • != Not Equal to
  • === Equal to with datatype check
  • !== Not equal to with datatype check

Q 23. How you can clone an object in JavaScript?


Answer. Object.assign() method is used for cloning an object in Javascript.

Syntax:

 var x = {myProp: "value"};
 var y = Object.assign({}, x); 

Categories
Backend Developer Development Express Javascript Node

What Really Makes Node.js Great?

Javascript- That is actually playing a drastic role to make Node.js great. As it is well known that Javascript is favorite to most of the software developers to build applications because Node.js uses javascript as its main framework. The Node.js community is used to create a scalable application.

After specialising in Ruby on Rails for a while, I realised that the time has come for me to expand my skill set. I wanted to move on from working move on from working mostly on small-scale apps into more ambitious projects for large corporate clients. Node.js was the obvious choice, because I already knew JavaScript and was aware that the market value of Node.js skills would only grow.

-Michal Hartwich
nodejs


Why Node.js is a standard programming language to enterprises for large-scale apps?

REASONS:

  1. Make real-time applications fast.
  2. In node.js coding in JavaScript is possible for both the client and server-side.
  3. Increase efficiency in the developing process.
  4. Execution of coding is faster than other languages and boost productivity.
  5. As well as perfect for Microservices.

You read about Node.js and its uniqueness that makes it great among all. Lets first start with the intro part.

Why it is great?

Node.js is a cross-platform, and open-source, JavaScript run-time environment that executes JavaScript code outside the browser. Though .js is a filename extension for JavaScript, that allows the developer to use Javascript to write the command lines for server-side scripting to produce dynamic web page content.

Corporate users of Node.js software are LinkedIn, Netflix, Microsoft, and so on. As Node.js has an event-driven architecture that capable of asynchronous I/O (It is a form of input/output processing that permits other processing to continue before the transmission). It aims to optimize scalability in web applications.

Helping Hands- Node.js Frameworks:


To smoothen your application development, here are some excellent Node.js frameworks to build your applications more effectively.

1. Design your web application with Express.js


Express is a web application framework for Node.js developed by T J Holowaychuk. It is free and open-source software under the MIT License. It is designed to build web applications and APIs.

The other name for Express.js is a minimalist framework. It is a single-threaded, open-source and fast Node.js framework used for web and mobile app designing. This framework is easy to understand. It allows easy integration of third-party services and seamless I/O approach.

Several NPM modules can be integrated into Express.js for better operations. The back-end of a MEAN stack is developed by Express.js and MongoDB, with AngularJS in the front-end. Express.js is described by an event loop and non-blocking I/O.

2. Developer supportive- Nest.js


Nest.js is a server-side (backend) application framework to support the developer’s productivity. Nest framework is a TypeScript characterized by Dependency injection, authentication, stack, ORM and REST API.

nestjs


Development with TypeScript using nest.js employs code writing by juxtaposing various programming types such as functional programming, object-oriented programming, functional reactive programming, etc. However, the tools used in nest.js need improvement for enhanced performance.

It is an event-based that allows the scalability of microservices. Nest.js provides the developer flexibility that allows using any libraries of Node.js. It is versatile as well as progressive.

3. Ironic Meteor.js


This Node.js framework employs isomorphic JavaScript code for mobile and web app development. Meteor.js is an MVC-based and open source and provides a highly effective front-end solution. It allows a highly efficient client-server interface, seamless debugging, live reload, database integration and real-time testing.

Meteor.js

Though it has few loop-holes like lack of server-side rendering, the absence of in-build PWA support, the absence of MongoDB support, etc. , meteor.js still stands out as an excellent framework with its simplicity and versatile libraries and packages.

OMG! It amazes the developer’s experience.


Node.js is used for real-time application and Node.js is open source cross-platform runtime environment has been written in JavaScript. The top choice of a developer in the web application development is Node.js because it comes with new features.

It also allows developers to make web servers and networking tools with effective use of JavaScript.

  • Node.js Is Very Fast:

Node.js use V8 engines by Google. Google engines V8 (JavaScript → V8(C++) Machine Code) which compile JavaScript into native machine code and runs very speedy and because of it, Node.js increase any framework’s speed. It helps enterprises build fast, flexible network applications that can handle parallel connections with high throughput.

  • Stimulate Sharing:

Node.js boosts imparting to the approach the Node Package Manager or NPM. With the inbuilt NPM, developers can restore, share or reuse codes within with clicks. Along these lines, it tends to be proved that Node.js bundle supervisor is strong and a steady answer for designers.

  • Node.js Make For Real-Time Web Application:

It has unbelievable features when it comes to creating real-time applications such as chats and gaming apps. Also good for the programs that need an event-based server, as well as non-blocking driven servers.

  • Single Code Base Web Application:

The developer writes JavaScript for server and client, by making it easy to send data between the server and the client for synchronization.

  • Data Streaming:

Web frameworks treat HTTP requests and responses as whole data objects. Node.js is very good at handling I/O, So it can use as an advantage for the developer to build some amazing web application. Node.js can also read and write streams to HTTP.

  • Every Developer Know JavaScript:

Every web coder has coded a little bit of JavaScript, even if that JavaScript was hacking a jQuery plugin. Nowadays, it is hard to find web developers. And Node.js is easy to learn if the developer familiar with JavaScript.

  • Increase Productivity:

Productivity must not be sighted as a one-dimensional character, but a multidimensional one. A developer is more productive in Java because of compile-time errors. Enterprises can add the frontend and backend teams into a single unit so application delivers in less time with high productivity.

Even if we had a language that made writing callbacks easy (like C#), we’d need a platform that minimal to no blocking I/O operations.

Node.js- What So Special..!!

The Node.js server technology is used to create & run high variety of web applications, it is quite similar to Ruby on Rails does. Its main language is JavaScript which is lightweight and manages the plenty plugins via Node Package Manager (NPM), that allows the developers to custom-build applications.

There are no different languages for back-end and front-end developers, Node.js uses the same language for both of them that make it easy to create apps.

The Back-end applications directly interact with the database via an application programming interface (API) that pulls, saves, or changes data, whereas the Front-end codes interact with back-end sever to drag out the data on the front-end user interface (UI) side.

But with Node.js, both (Front-end and Back-end) merged and work together instead of pulling each other to different directions of working.

Every developer is familiar with JavaScript which is the main reason for Node.js to build and compile applications easily, there is no other language to create or build any API and UI applications in node.js. It decreases the complexity by performing the code.

Node.js boost both front-end and back-end and acts as the best of technology to develop apps. This means that your team will be more efficient and cross-functional leading to lower development costs. In addition to this, it is worth mentioning that JavaScript makes your codebase with much easier platforms. Secondly, you can also then reuse and share the code between the backend and the frontend of your application that speeds up the development process.

The complete js technology stack is open-source & free and that is good news. Finally, Node offers you a complete package for every possible thing that developers are looking for.

TOP 5 SEARCH ENGINE QUERIES ON NODE.JS


Why Node js is Used?

Node.js is an excellent platform built on Chrome’s JS runtime for developing, building a fast, scalable for network applications.

Is Node.js a programming language?

Node.js connects the efficiency of a scripting language with the power of Unix network programming. It is proficient with internet fundamentals such as HTTP. Therefore, Node.js is not a programming language but a Scripting language in JavaScript.

Is Node.js same as JavaScript?

Simply, JavaScript is a programming language that runs in any browser of JavaScript Engine, but on the other hand, Node.js is an interpreter of JavaScript, which holds the relative or you can say similar libraries of it for better use. So, they are not the same but, follows similar libraries to build applications.

What is Great about Node js?

The great thing about Node.js is, it uses event-looping instead of the strings. Excessing web services, reading along with the files and then making a file to wait until it’s completely get uploading because such operations are mostly slow then the memory execution operations. Every input/output operation in the Node.js is asynchronous. Sever continue to process all the Input-output operations. It makes scaling and processing between the programming events easy.

What are the benefits of using node.js for a startup?

benefits of Node.js:
1. Node.js is scalable.
2. It boosts your development speed.
3. Requires a low learning curve if you are familiar with JavaScript.
4. Take less time to run any program.

Categories
Development Frontend Developers Javascript Node ReactJS Startup Top Coder

Nuxt, Next, Nest! Confused?

Programming is the method to innovate something new and amazing. Being a coder, it is important to be aware of every new upcoming technology. “Nuxt”, “Next”, “Nest” a little confusing, right? They might sound similar but their practical application is different from each other.

The coders who aren’t familiar with these frameworks might get confused in the beginning, these are the perplexed and complex words. I’m going to explain all the concepts of Nuxt, Next, and Nest so stay tuned with me, in this article you may explore the uses and the installation of these frameworks. Surely, this article will help you to know about these frameworks in depth.

Do you ever think why do we actually need a framework? What are the uses of the framework?

  • A framework is a platform that provides a foundation on which software developers can create programs. It allows the coder to make robust applications.

  • Also, the framework provides diversified support for developing robust applications with pace and ease because it provides a standard way to build and deploy applications.

Before starting with these frameworks, let’s have a short briefing of CSR (client-side rendering) vs SSR (Server-side Rendering).

  • By these platforms, it is important to understand that Vue and React are the client-side Rendered (CSR) framework, which makes the page interactable and viewable.

WORKING OF CSR

📤 Server sending the response to the browser 📤

📥 Browser downloads JavaScript 📥

💬 Browser executes React 💬

🌐 The page now viewable and interactable 🌐

  • Using these platforms, Server-side Rendered (SSR) use to make the page interactable.

WORKING OF SSR

👩‍💻 Server sending ready to be rendered
HTML response to the browser
👩‍💻

📥 The browser renders the page, Now viewable
and browser downloads JavaScript
📥

🆗 Browser executes React 🆗

🌐 Page now Interactable 🌐

The first thing that needs to be clear is these three frameworks- Nust, Next, and Nest are different from each other but comes in Javascript Ecosystem.


If you’re a Vue.js programmer, then you probably heard of Nuxt.js. or if you’re not then let starts with Nuxt!

What is Nuxt.js?


Nust.js is a high-level framework that builds on Vue. It is an open-source application framework that is free and based on Vue.js, also Node.js, Webpack, and Babel.js. Nust comes under universal application which uses “meta-framework” as well as develops single page Vue apps.

The main aim to build applications with Nuxt.js that it is more flexible while creating any project because Nuxt helps the developers to create complex, fast, and universal web applications quickly.

What is Vue.js?

It is an open-source Javascript framework, it is faster as well as smoother to build user interfaces and single-page applications. The reason behind this is, Vue had familiar templating syntax and use of components, integrating or migrating the project make it more understanding by the beginners. For this reason, Vue is the best framework for tech startups or beginners to learn and build applications. Also, useful for large-scale applications as performance-wise.

[Important] The current version of Nuxt.js is v2.9.2

Reasons why the developers consider Nuxt for any project:

1. Build universal apps without any trouble.


The plus point of the Nuxt.js is that the developers can create universal applications easily in the Vue. Most of the people are not familiar with universal apps basically the beginners.

So, what is a universal app?

It is the app that describes JavaScript code that can execute both on the client and the server-side. There are many modern Javascript frameworks like Vue, that aim to build Single-page Applications (SPA). And a universal app completely based on SPA.

  • Nuxt makes coding more simple:

    It is boring to build long monotonous projects for developers because it needs more time for the configuration on both server-side and client-side. The main aim is to make it simple to share codes between server and client.

    Last but not least, Nuxt gives the developer an asyncData method in the components which use to fetch data and render it on the server-side. This is how Nuxt helps the developers to create universal applications.

2. Provide automatic code-splitting


Nuxt generates a static version of your website with a unique webpack configuration. For every page, it automatically creates the program which builds its own JavaScript file.

Also, it helps to speed up the progressing and keep the size of the JavaScript file small relatively to the application size.

3. Easy to write Single file components


There are many Vue projects using Vue.component, supported by new Vue ({ el: `#container’ }) to target the container element in the body of every page. It is used only to build small projects (single file) where JavaScript is only used to enhance certain views. It has difficulty managing the big file. Use .vue extension with single-file components, to solve your problem.

The installation process of Nuxt.js

  • Syntax to Install Nuxt:
$ npm i nuxt
  • Syntax to create a basic application:
$ npx create-nuxt-app <project-name>

According to the latest update, you can directly start with the CLI create-nuxt-app.

Or start it with a simple template: starter:
The basic Nuxt.js project template express: Nuxt.js + Express koa: Nuxt.js + Koa adonuxt: Nuxt.js + AdonisJS micro: Nuxt.js + Micro nuxtent: Nuxt.js + Nuxtent module for content-heavy sites.

  • Example: Syntax for a basic Hello World app in Nuxt.js
<template>
  <div>
    <h1>Hello world!</h1>
    <NLink to="/about">
      About Page
    </NLink>
  </div>
</template>

Advantages of Nuxt.js

  • The main advantage of Nuxt.js is, its main scope is UI rendering while removing away the client/server distribution.

  • In Nuxt.js you get automatic code-splitting.

  • Statically its render your Vue apps and get all of the benefits of a universal app without a server.

  • You can easily set up transitions between your routes and write single-file components.

  • It provides an auto-updating server for easy development.

  • In Nuxt.js you get ES6/ES7 compilation without any other extra work.

After clear our first concept of Nuxt. Let’s move to the next topic Next.js

next.js


If you compare all three frameworks, the most popular framework you get is Next.js from the other two. Let see what is so interesting in this framework that it is popular and developer’s favorite.

What is Next.js?


Next.js is a Javascript framework that uses React to build server-side rendering and static web applications. According to every developer, it the best tool to build websites because it has great features and advantages, which make it the first option for creating web applications.

So, do you think, why it is the first choice of the developer for building web applications?

The first thing that makes it different from the other two frameworks is it doesn’t need any configuration of webpack. Even it comes with its configuration, with some basic React and Javascript knowledge, build your way to development.

Some of you all know about React, but for beginner, let’s have a quick introduction to React.

What is react?

React is a Javascript library for building user interfaces, it is also known as React.js. It can be used as a base in the development of single-page or mobile applications that make it optimal for fetching rapidly changing. React was created by Facebook.

For using React.js it is important to know about the basic components of React.

Components cab be rendered to a particular element in the DOM by using the React DOM library. There are two primary components in React.

  • Functional components

These are the component which declared with a function that then returns some JSX.

Syntax:

function Greeting(props) {
  return <div>Hello, {props.name}!</div>;
}
  • Class-based components

These are the components declared using ES6 classes and also known as “stateful” components, because their state holds the values throughout the component and can be passed to child components through props.

Syntax:

class ParentComponent extends React.Component {
  state = { color: 'green' };
  render() {
    return (
      <ChildComponent color={this.state.color} />
    );
  }
}

This is all about React let come to our topic Next.js.

Next.js is a framework that is opinionated and provides a structure for the apps. As well as it is an automatic code-splitting.

[Important] The current version of Next.js is Next.js 9

Some reasons to use Next.js to build your project.


Next.js comes with great features that make it useful as well as popular among the developers.

1. Easy to generate website


For beginners or experienced developers, Next.js is the framework easy to use and get started to build a project. It is easy in Next.js to compile and export the application in HTML.

2. Server-side rendering


Next.js performs server-side rendering by default which makes your application optimized for search engines. In this Next.js come with a head component that allows the developers to add or make dynamic Meta-Tags.

By using SSR you get:

  • It provides users an initial render of the applications while loading the code in the background.
  • Easily eliminate the need for the client to download code in HTML format.
  • Also, help to create SEO friendly applications.

3. Routers


When you create any React application by using create-react-app, you usually need to install a react-router and create its custom configuration. But with Next.js it is easier because it comes with its own routers with zero configuration. The main feature is that Next.js take care of all its routers you just sit and create your page inside the pages folder.

The Installation Process of Next.js

  • Syntax to install Next.js:
npm install --save next react react-dom
  • Syntax to add a script to your package.json:
{
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  }
}

After that, the file-system is the main API. Every.js file program that gets automatically processed and rendered.

  • Example: Syntax for a basic Hello World app in Next.js

Use ./pages/index.js inside your project

function Home() {
  return <div>Hello world!</div>;
}

export default Home;

Then run npm run dev.

Advantages of using Next.js

  • Next.js is easy to deploy anywhere with Node.js support.

  • It can be executed with Express or any other Node.js HTTP server.

  • Any unnecessary code is not loaded in Next.js.

  • Webpack-based dev environment which supports Hot Module Replacement (HMR).

  • Fetch data easily.

  • Next.js is simple client-side routing (page=based).

  • Every component is server-rendered by default in Next.js.

  • As well as, automatic code-splitting which use for faster page loads.

Here we complete our two concepts Nust.js and Next.js, let’s move to the last topic Nest.js

nest.js


The main thing that makes Nest.js differ from both the frameworks is that it is heavily inspired by Angular.

What is Nest.js?


Nest.js is a framework for building efficient, scalable Node.js server-side applications. It is the modern JavaScript, which is built with TypeScript and uses Express.js. The important thing that Nest.js provides that it preserves compatibility with pure JavaScript and the combine elements of OOP (Object-Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).

As similar to TypeScript and a reasonable knowledge of JavaScript help the developer to create the best application in Nest.js. The main aim of Nest.js was to solve the architectural problems of Node.js by providing back-end applications a modular structure for organizing code into separate modules. The plus point to work in Nest.js that it is fully built with TypeScript which is really beneficial for code type checking by which it helps to facilitate the process of development of the application.

[Imprtant] The current version of Nest.js is version5

Recently, the Nest.js framework is increasing popularity due to its incredible features:

Some features of Nest.js

  • Nest.js is open-source (MIT license).

  • It is easy to use, learn and develop applications.

  • It is a powerful command-line interface (CLI) tool that boosts your productivity.

  • It has detailed and well-maintained documentation.

  • Also, supports specific modules that help you easily integrate with common technologies and concepts such as TypeORM, Mongoose, GraphQL, Logging, Validation, Caching, and Websockets.

  • Also, provide active codebase development and maintenance.

  • Leverages typescript which means it is a strongly typed language that super-set of JavaScript.

  • Easy to unit testing applications.

  • The Nest.js is made for Monoliths and Micro-services (entire section in the documentation regarding the Microservice type of a NestJS application, as well as techniques and recipes).

Nest.js provide the developers with an out-of-the-box application structure that allows them to create highly testable, scalable and easily maintainable applications. As well as it makes use of Express which provides compatibility with a wide range of other libraries that the developer easily uses the myriad third-party plugins which are available.

The Installation of Nest.js

  • Syntax to install Nest.js
$ npm i @nestjs/cli
$ nest new project-name
  • Example: Syntax for basic Hello World app in Nest.js

    Remember, after installing Nest.js with the npm cli command, and to create a new project with nest new project-name.
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);
  await app.listen(2000);
}
bootstrap();

And then to run the app listen on port 2000, you execute the syntax:

$ npm run start

Advantages of using Nest.js

  • The main advantage of the Nest.js is that it has a TypeScript-based web framework, that possible to build any strict type application.

  • The framework of Nest.js is very annotation-driven which generates everything to make you easy.

  • The project that builds in Nest.js is heavily based on Angular.

  • As you know Nest.js is a module-based framework, by which it is easy to externalize general-purpose modules and reuse code in multiple projects.

  • The important advantage of the Nest.js is that it uses the latest version of TypeScript that helps the developers to code less and gets productive work. And this is the same with Angular.

Just Remember

Nust– This is the framework to create a Vue application that supports universal rendering.

AND

Next- This is to create a React application that also supports universal rendering.

AND

Nest– This for node applications with additional structure and support.

Categories
Development Frontend Developers Javascript Node Remote developer

What is Scala used for? | A Brief Overview


Scala is a general-purpose, object-oriented programming language. It provides support to functional programming. It also helps in avoiding bugs in complex applications. In this article, you get to know about Scala and what is Scala used for?

Introduction

Scala is a programming language invented in the year 2003 by Mr. Martin Odersky and his team. Scala released publicly in 2004 on the Java platform. The name Scala is a blend of scalable and languages. That signifies it designed to grow with the demands of its users.

  • Scala is a Robust and High-Caliber programming language.
  • It is also capable to outrun the speed of the fastest existing programming languages.
  • it’s a compiler-based and a multi-paradigm language.
  • Which makes it compact, fast and efficient.
  • Scala uses Java Virtual Machine(JVM) for compilation.
  • Firstly Scala Compiler compiles the Scala code and generates the byte code for the same.
  • After that, it transferred to the Java Virtual Machine to generate the Output.

Platforms And Compilers


Scala runs on the Java Platform(JVM). So it is compatible with all the existing Java programs. Even its compatibility with JAVA makes it well-suited to Android development. Because Android applications typically write in Java and translate from Java bytecode into Dalvik bytecode when packaged.

Let’s talk about some Scala compilers:-


Scala.js:-

  • Scala.js is a Scala compiler.
  • It compiles to JavaScript.
  • Scala.js compiler makes it possible to write Scala programs that can run in web browsers and also in Node.js.
  • The compiler was in development since 2013. But launched in 2015 with the version name(v0.6).


Scala native:-

  • Scala native is also a Scala compiler.
  • That mainly targets the LLVM compiler infrastructure to create executable code.
  • It uses a lightweight managed runtime. Its first release was 0.1 on 14 March 2017.
  • The motive behind developing scala native is being faster than JIT compilation for the JVM.
  • It achieved by eliminating the initial runtime compilation of code and also providing the ability to call native routines directly.

Key Features Of Scala

  • In Scala, there are no static variables or methods. Scala uses singleton object, which is essentially class with only one object in the source file.
  • Here you don,t require to mention data type and function return type explicitly. Scala is enough smart to deduce the type of data.
  • In Scala evaluation is lazy by default. Scala evaluates expressions only when they are required.
  • Scala provides a standard library that includes the actor model. So you can write concurrency control.
  • Higher-order functions are the function that either takes a function as an argument or returns a function.

What is Scala Used for?

Scala has the capability to interpolate with the existing Java code and libraries. It is mainly a static type language. There is no concept of primitive type data in Scala. It is a multi-paradigm language that supports multi-core architecture. The main uses of Scala are described below.

Statically Typed language:-

Scala feels dynamic but it is strongly statically language. It provides type interface for variables and functions. A statically typed language avoids the mistake in code and also helps programmers to write proper code and debug code easily. But in dynamic languages, errors are visible only when you run a program.

Example:-

def dup[T](x: T, n: Int): List[T] = {
if (n == 0 ) Nil
else
x :: dup(x, n - 1)
}
println(dup[Int](3, 4))
println(dup("three", 3))

Method dup is parameterized with type T and value parameters x: T and n: Int. Scala type system automatically infers the type of the parameter according to the value.

Built-in Practices And Pattern:-

Scala was developed with the intention of creating new innovations in programming language research to mainstream languages like Java. This language already has some best practices and patterns that are built in the language. It also offers to adopt new languages like Python, Ruby, etc to implement functional programming.

Pattern matching lets check a value against a pattern. You can use this in place of a switch statement or a series of if-else statements in Java.

import scala.util.Random
val x: Int = Random.nextInt(10)
x match
{
case 0 => "zero"
case 1 => "one"
case 2 => "two"
case _ => "many"
}


More Expressive:-

Scala is inherently more expressive than Java. One who learns Scala after Java finds it easier as well as interesting. Let understand it by this example:-

Java code:
Public class wordcount{
Public static void main(String [] args){
StringToken st= new StringToken(args[0]);
Map<String, Integer> map= new HashMap<String, Integer>();
while(st.hasMoreTokens()) {
String word= st.nextToken();
Integer count= map.get(word);
If(count == null)
map.put(word, count+1);
}
System.out.println(map);
}
}
Scala code:
Object WordCountScala extends App {
Println( args(0).split(“ ”).groupBy(x => x).map(t => t._1 -> t._2.length))
}

Multi-paradigm

Scala supports both kinds of programming object-oriented programming as well as functional programming. you can easily explore both sides of functional and OOP together. You are able to define different types associated with both data attributes and behavioral attributes. Scala functions allow you to pass values and also supports anonymous functions.

Inter-Operability:-

The interoperability feature of Java is one of the best options in Scala. This enables Scala developers to use all libraries of Java directly from Scala code. It is also possible to call Scala code from Java and the user can easily write any part of a program in Scala and rest in Java.

Demanding:-

The main use of scala is better growth and job. Scala will help to increase your demand and will make you even more marketable. Many companies like Twitter, LinkedIn, Foursquare, etc are using Scala.

Frameworks:-

Scala provides various libraries that can be used to build many frameworks. There are already many frameworks that have come to existence like Lift and Play. Akka is another Scala-based framework. IT is concurrent and established like a toolkit.

Precise Syntax:-

Scala has a very precise syntax as compared to Java. Java has very long syntax. Scala’s, this feature makes it more readable and concise. ScalaC can generate and work for better code.

Easy To Learn:-

Scala’s object-oriented functionality makes it easy to learn. Scala has clean syntax, nice libraries as well as good online documentation.

Advantage and Disadvantage

  • Highly functional
  • Great for analytics
  • Good IDE support
  • Inherently immutable object
  • Limited community presence
  • Hard to learn
  • Lack of ease of adoption
  • Limited backward compatibility

Scala Frameworks And Libraries

How to write Scala programs

Here I am giving you a small example of how you can write Scala program. Firstly, you need to install Scala on your machine. And you must have to install jdk on your machine because Scala compiler creates .class file which is byte code. Scala interpreter executes this byte code by using jvm.

Example:-

object ScalaExample{  
    def main(args:Array[String]){  
        println "Hello Scala"  
    }  
}  

In the above code, you created an object ScalaExample. It contains a main method and display message using printIn method.

This file is saved with the name ScalaExample.scala.
Command to compile the code is : scalac ScalaExample.scala
Command to execute the compiled code is: scala ScalaExample
After executing code it will give the following output:-

Hello Scala

By using functional approach

def scalaExample{  
    println("Hello Scala")  
}  
scalaExample            // Calling of function

Output

Hello Scala

Versions Of Scala

By now many versions of Scala has been launched. At present Scala 2.13 is in use. Scala 3.0 will release in start of 2020. Features it will contain are:-

  • Scala 3.0 will promote programming idioms.
  • It will be more simplified.
  • It will consolidate language constructs.
  • This will improve consistency, performance, and safety.

Scala Vs Other Languages

Scala has been in a tough fight to overthrow Java. Java has remained one of the most popular, versatile programming languages since the time it was created. Scala was introduced with the intent of addressing many of the concerns developers have with Java.
Where many programming languages trying to compete with Java have failed, Scala has succeeded.
The language, built on top of the JVM, consists:
-Compatibility with Java
-Interoperability

Same as Java, Scala often compared with python. Python and Scala are the two major languages for Data Science, Big Data. Python and Scala both are object-oriented languages.

Let’s go throw some more specific points about Java, Scala, and Python:-

Java

  • Java is a programming language developed by Sun microsystems in 1995.
  • Developers choose Java because it has great libraries, widely used Excellent tooling and a huge amount of documentation available.
  • Some cons of Java are verbosity, NullpointerException, Overcompexity is praised in community culture and bloat.
  • Companies that use Java:-
    Airbnb
    Uber Technologies
    NetFlix
    Spotify
    Instagram
    Pinterest

Scala

  • Scala is an acronym for Scalable language. that means is Scala grows with you.
  • This language provides Static typing, Pattern matching, types. Scala uses Java Virtual Machine for compilation. Overall Scala is a fun language to use.
  • Cons of Scala are slow compilation time, too few developers available, Multiple ropes to hang yourself.
  • Companies that use Scala:-
    Twitter
    Coursera
    9GAG
    Asana
    Groupon
    Reddit

Python

  • Python is a general-purpose programming language, created by Guido Van Rossum.
  • It has great libraries, Readable and beautiful code. In Python development is rapid.
  • Python cons are:- still divided between python 2 and python 3, poor syntax for functions. Package management is a mess.
  • Companies that use Python:-
    Dropbox
    Uber Technologies
    Netflix
    Instagram
    Spotify 

Technologies Written In Scala

  1. Apache Spark
  2. Scalding
  3. Apache Kafka
  4. Finagle
  5. Akka
  6. ADAM
  7. Liches

Future Scope

As mention, Scala has many uses once you learn it, In the future, it will surely increase Scala developer’s value in the market. They will be able to develop new frameworks and use the dynamic feature of this language. Scala being trending largely all over the world.

Categories
Frontend Developers GraphQL Javascript Node React Developers React Native Developers React Native Web Remote developer Top Coder

4 Great Ways US-Based Company Can Hire Software Developer



Most software development companies in the US facing issues in the hiring of software developers. Due to the lack of local talented professionals.

Although the graph of technical graduates is in increasing order. Still, top-rank companies like google and apple with their high packages and perks find it challenging, hire well-skilled software developers.

It may be a difficult and expensive task to do. But, hire a top coder or developer is not something that is impossible.




First of all, before hiring a software developer there are some things you should keep in mind.


Every software developer who walks around for an interview comes with a different skillset. And every employer searches various skills and attitudes. There are various factors that fill help you to find the right software developer for you.


Analytical Thinking:-

As a software developer, a person should have an analytical approach. This gives you better thinking and observation power to understand things more deeply.

It makes you creative and productive. Before hiring a software developer, give it a sight to his/her analytical thinking.


Communication:-

If you are in one of who thinks communication skills are not important as a software developer. Then you are absolutely wrong. Most people think if a candidate has well technical skills then you can ignore his/her communication skills.


End of the day he/she is going to do coding designing. But what about sharing the idea? don’t forget development is teamwork. you have to share your idea with your respective team. And for them to understand you need to communicate with them well.


Coding:-

Obviously, coding is the key point if you going to hire a software developer. A software developer without the best coding skills is for no use.


As a software developer, we have to work on the best programming languages that are not user-friendly. But highly demand technologies like Node.js, react native, react native web, AngularJS. so a software developer should have extreme knowledge of coding.


Attitude:-

“Skill can learn not the attitude”. A positive attitude leads towards a positive end. If an employee with a negative attitude will impact on other employees.

Because of that indirectly the work going to suffer. So a software developer having a positive attitude toward their work is important.


Work ethics:-

Work ethics are very important for any employee. If an employee doesn’t have any work ethics he/she will go office late, will not complete his/her on time. That will impact on other employees too.

So for the sake of professional discipline and a proper workflow give it sight on employee’s work ethics.




There are many alternatives approaches you can choose to hire a software developer. We will look upon it all one by one.


1- Traditional way

There was a time when for a software developer role you need a respective degree. But now the technology changes day by with laser light speed developer with current skillset are required.


To learn these skills no college degrees are needed. One can learn these skills from books or join some online courses. So it easy to update your self with the current skillset.


So according to the current trend if you are going to hire a software developer, give priority to experience and knowledge over some professional degrees.


Check Portfolio:-

The best way to check your developer’s experience and skills are the portfolios. As everything is mention in the portfolio you can have knowledge about their past projects.

And the clients for whom they work for. You will get to know what technologies they used in their past projects and experienced them. Or what new skills they are learning and from where.

Then it easy to decide for you. whether the candidate is fulfilling your profile needs or not.


Candidate availability:-

It’s not only developers look for a new opportunity you should also keep an eye on the pool of best developers. Just like if you want to buy any property that is not free now you will keep an on it till then its available for.

Its the same with software developers if you think for some developer that only he/she can get understand your project. And deliver you the best product to keep an eye on him/her. Some developers only available for new recruits when they get a finish from one place.

So if you will track them regularly you get to know when they are going to free and hire them for your project.


2-Hire Remote Developer

Hire a remote developer could be a great option for you. If you are also one of them who can break the geographical boundaries for the sake of technology and skills.

Then this is the best option for you. there are a lot of talented well-skilled developers in the world you just need to shift your eyes from the local talent to the global.

If your project is core technology-based then don’t compromise with the quality of your project just for the ease of hiring local talent. Increase your search area and find the best fit for your project.




Pros of hiring a Remote developer:-

  • You can access to the global talent pool.
  • lots of resources you can get this way.
  • You don’t need to spend on infrastructure and benefit.
  • Costs are potentially lower here.


Cons of hiring a Remote developer:-

  • Chances of data leakage are more.
  • The deadline could be unmet.
  • Time differences could occur.
  • Communication barriers.
  • Unreliability is also an issue here.



So these were some cons and pros of hiring a remote developer. Consider it once if you are going to work with remote developers.


3-Outsourcing companies

If you want to hire a whole new team for your project. And you are not able to get talent what you required. Outsource companies are best for you.

These days finding a skilled software developer is already a difficult task to do upon that you need a whole team to manage that. This could be the most time-consuming part. Outsourcing could help you with this.

You can save your money or not this depends on where you choose to outsource. But definitely, you are going to save a lot of time and resources. That you can use in your project.



Pros of outsourcing:-

  • You can hire multiple developers at once, rather than having to assemble a team one by one.
  • Possible cost saving(depending on the outsourcing location.


Cons of outsourcing:-

  • Loss of managerial control. And insight into the vendor’s process.
  • Low quality of work due to developers working on many projects.
  • Cost overages, as changes to the end product, are priced individually.


These were some pros and cons of outsourcing. Consider them before taking the help of outsourcing companies.


4-Your own development team

There two ways you can make your development team. First the traditional way of hiring second the remote way you can choose likewise.

If you are going to hire local talent for your development team then you have to spend a lot of time and money. Because you needed to hire a few employees then trained them.

Then you need a space where they will work and some other facilities. But if you choose to create a remote development team time and money will-less spend.


Offshoring works Best when:-

  • You need experienced engineers and engineers skilled in rare technologies. But you can’t find them locally.
  • You want to manage the development process directly but not ready to open your own office.
  • You are looking for an open and secure way to grow your development team.


Pros of Offshoring:-

  • Full involvement in the hiring process.
  • Full control over the development process.
  • Full-time developers exclusively working for you.
  • No need to spend on infrastructure.


Cons of offshoring:-

  • Require an inhouse tech specialist, capable of running a development team.
  • Not a good fit for short term projects.
  • 4-6 weeks to build a team.



So these are some methods of hiring software developers. Consider these methods and check which one is the best fit for you.

Categories
Express GraphQL Javascript Node

Nestjs Typeorm Graphql Dataloader tutorial with Typescript


# All source is available here, you can either download 
# or follow the tutorial below to understand 
# each and every component individually  


https://github.com/codersera-repo/typeorm-graphql-nestjs-dataloader-starter-kit 

Before we deep dive into integrating all three into a single project. And to take advantage of GraphQL query language, and Typeorm relational database with PostgreSQL (PSQL) or MySQL or any other DB. Let’s understand the individual pieces separately.

I assume that you have basic knowledge of ORMs, Express, Node, Graphql, NestJs. In case you are missing not, here is the brief introduction

GraphQL

GraphQL is a query language for the API. When a request (query in GraphQL world) triggers, It decides the data flows over the network.

Graphql trigger requests using a smart single endpoint unlike in traditional REST API. Where an endpoint is triggered according to the data and resource.

NestJS

NestJs is a framework used to serve our server needs. It uses Express and Fastify under the hood and has robust support for TypeScript. Which is designed and employed to make the backend structured that is in easy to maintain modules.

TypeORM

TypeORM is an Object Relational Mapping Tool that can be used with DataBase like Postgres, SQL, Mongo-DB. It supports multiple databases in the application and writing code in the modern JavaScript for our DataBase needs.

Lets us start building a basic author-books-genres program using TypeORM, NestJS, Graphql, RestAPI, Dataloader

1. Installing the NestJS and creating a scaffold project.

Either scaffold the project with the Nest CLI or clone a starter project (both will produce the same outcome).


npm i -g @nestjs/cli

nest new user-typeorm-graphql-dataloader

You can either choose yarn or npm, we are going with yarn route.

Install the dependencies for GraphQL, dataloader, typeorm, SQLite.

Once you have installed the new project, change your directory to the project we created and installed the following dependencies


yarn add dataloader graphql graphql-tools type-graphql typeorm graphql apollo-server-express voyager @types/graphql @nestjs/graphql sqlite3 @nestjs/typeorm

Create a .env file, where we will be putting our environment constants. For now, we will be using this file to populate the typeorm configuration and port where to run our servers. We are using SQLite for this tutorial purpose, but you can use any SQL database, typeorm supports multiple drivers

# .env 

TYPEORM_CONNECTION = sqlite
TYPEORM_DATABASE = data/dev.db
TYPEORM_LOGGING = true
TYPEORM_ENTITIES = src/db/models/*.entity.ts
TYPEORM_MIGRATIONS = src/db/migrations/*.ts
TYPEORM_MIGRATIONS_RUN = src/db/migrations
TYPEORM_ENTITIES_DIR = src/db/models
TYPEORM_MIGRATIONS_DIR = src/db/migrations
EXPRESS_PORT = 3000

Next, we need to create some directories, where our typeorm entities, typeorm migrations, and SQLite database are gonna resides


mkdir -p src/db/models  # our entites here
mkdir -p src/db/migrations # our migrations here
mkdir -p data # here our sqlite.db

Creating our Migrations

We gonna use typeorm CLI to generate our migrations, luckily typeorm migrations CLI come intact with typeorm package

  1. Author: We gonna create Author here
  2. Book: We gonna create Book here
  3. Genres: We gonna create Genres here
  4. BookGeneres: We gonna create Many-Many mapping between books and genres

That’s all the migration we need, below is the command to create typeorm migration since .env file already knows where to create migrations that we have already provided above.


 ts-node ./node_modules/typeorm/cli.js migration:create -n CreateAuthor    
 ts-node ./node_modules/typeorm/cli.js migration:create -n CreateBook 
 ts-node ./node_modules/typeorm/cli.js migration:create -n CreateGenre   
 ts-node ./node_modules/typeorm/cli.js migration:create -n CreateBookGenre 

The above commands should create 4 files in your src/db/migrations directory, here is how a single migration would look like.

# src/db/migrations/1563360242539-CreateAuthor.ts 

import {MigrationInterface, QueryRunner} from "typeorm";

export class CreateAuthor1563360242539 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<any> {
    }

    public async down(queryRunner: QueryRunner): Promise<any> {
    }

}

Typeorm uses epoch time as the prefix for migrations to run migrations in order. You can populate your migrations now with the creation of the table, here is how your migration should look like.


import { MigrationInterface, QueryRunner, Table } from 'typeorm';

export class CreateAuthor1563360242539 implements MigrationInterface {

    private authorTable = new Table({
        name: 'authors',
        columns: [
            {
                name: 'id',
                type: 'INTEGER',
                isPrimary: true,
                isGenerated: true,
                generationStrategy: 'increment',
            },
            {
                name: 'name',
                type: 'varchar',
                length: '255',
                isNullable: false,
            },
            {
                name: 'created_at',
                type: 'timestamptz',
                isNullable: false,
                default: 'now()',
            },
            {
                name: 'updated_at',
                type: 'timestamptz',
                isNullable: false,
                default: 'now()',
            }],
    });

    public async up(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.createTable(this.authorTable);
    }

    public async down(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.dropTable(this.authorTable);
    }

}


import { MigrationInterface, QueryRunner, Table, TableForeignKey } from 'typeorm';

export class CreateBook1563360267250 implements MigrationInterface {

    private bookTable = new Table({
        name: 'books',
        columns: [
            {
                name: 'id',
                type: 'INTEGER',
                isPrimary: true,
                isUnique: true,
                isGenerated: true,
                generationStrategy: 'increment',
            },
            {
                name: 'title',
                type: 'varchar',
                length: '255',
                isNullable: false,
            },
            {
                name: 'author_id',
                type: 'INTEGER',
                isNullable: false,
            },
            {
                name: 'created_at',
                type: 'timestamptz',
                isPrimary: false,
                isNullable: false,
                default: 'now()',
            },
            {
                name: 'updated_at',
                type: 'timestamptz',
                isPrimary: false,
                isNullable: false,
                default: 'now()',
            }],
    });

    private foreignKey = new TableForeignKey({
        columnNames: ['author_id'],
        referencedColumnNames: ['id'],
        onDelete: 'CASCADE',
        referencedTableName: 'authors',
    });

    public async up(queryRunner: QueryRunner): Promise<any> {
      await queryRunner.createTable(this.bookTable);
      await queryRunner.createForeignKey('books', this.foreignKey);
    }

    public async down(queryRunner: QueryRunner): Promise<any> {
      await queryRunner.dropTable(this.bookTable);
    }

}


import { MigrationInterface, QueryRunner, Table } from 'typeorm';

export class CreateGenre1563360272082 implements MigrationInterface {

    private genreTable = new Table({
        name: 'genres',
        columns: [
            {
                name: 'id',
                type: 'INTEGER',
                isPrimary: true,
                isUnique: true,
                isGenerated: true,
                generationStrategy: 'increment',
            },
            {
                name: 'genre_name',
                type: 'varchar',
                length: '255',
                isNullable: false,
            },
            {
                name: 'created_at',
                type: 'timestamptz',
                isPrimary: false,
                isNullable: false,
                default: 'now()',
            },
            {
                name: 'updated_at',
                type: 'timestamptz',
                isPrimary: false,
                isNullable: false,
                default: 'now()',
            }],
    });


    public async up(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.createTable(this.genreTable);
    }

    public async down(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.dropTable(this.genreTable);
    }

}


import { MigrationInterface, QueryRunner, Table } from 'typeorm';

export class CreateBookGenre1563360276498 implements MigrationInterface {

    private genreBookTable = new Table({
        name: 'books_genres',
        columns: [
            {
                name: 'id',
                type: 'INTEGER',
                isPrimary: true,
                isUnique: true,
                isGenerated: true,
                generationStrategy: 'increment',
            },
            {
                name: 'book_id',
                type: 'INTEGER',
                isNullable: true,
            },
            {
                name: 'genre_id',
                type: 'INTEGER',
                isNullable: true,
            },
            {
                name: 'created_at',
                type: 'timestamptz',
                isPrimary: false,
                isNullable: false,
                default: 'now()',
            },
            {
                name: 'updated_at',
                type: 'timestamptz',
                isPrimary: false,
                isNullable: false,
                default: 'now()',
            }],
    });

    public async up(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.createTable(this.genreBookTable);
    }

    public async down(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.dropTable(this.genreBookTable);
    }

}

Once migrations are setup, you need to run Typeorm migrations now, Typeorm provides a very easy to use CLI to run all the migrations, it will create a migrations table in the database, where it will keep a record of all the migrations it has applied.


ts-node ./node_modules/typeorm/cli.js migration:run

Once you execute this command dev.db file in created in src/data folder, Use SQLite browser to view the database, it must have all the tables you created and also the migration table

Creating our Model entities to map our database tables.

Let’s create Entity now, we are going to use typeorm data mapper method for our models, However, if you want to use typeorm active records, then you just need to extend all your Models from BaseEntity class which can be imported from like


import { BaseEntity } from 'typeorm';
class Auther extends BaseEntity
......
# src/db/models/author.entity.ts

import {
  Column,
  CreateDateColumn,
  Entity,
  OneToMany,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';
import Book from './book.entity';

@Entity()
export default class Author {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @CreateDateColumn({name: 'created_at'})
  createdAt: Date;

  @UpdateDateColumn({name: 'updated_at'})
  updatedAt: Date;

  // Associations
  @OneToMany(() => Book, book => book.authorConnection)
  bookConnection: Promise<Book[]>;

}


import {
  Entity,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
  Column, OneToMany,
  JoinColumn,
  ManyToOne,
} from 'typeorm';
import BookGenre from './book-genre.entity';
import Author from './author.entity';
import { Field, ObjectType } from 'type-graphql';

@ObjectType()
@Entity({name: 'books'})
export default class Book {

  @Field()
  @PrimaryGeneratedColumn()
  id: number;

  @Field()
  @Column()
  title: string;

  @Field()
  @Column({name: 'author_id'})
  authorId: number;

  @Field()
  @CreateDateColumn({name: 'created_at'})
  createdAt: Date;

  @Field()
  @UpdateDateColumn({name: 'updated_at'})
  updatedAt: Date;

  @Field(() => Author)
  author: Author;

  // Associations

  @ManyToOne(() => Author, author => author.bookConnection, {primary:
      true})
  @JoinColumn({name: 'author_id'})
  authorConnection: Promise<Author>;

  @OneToMany(() => BookGenre, bookGenre => bookGenre.genre)
  genreConnection: Promise<BookGenre[]>;
}


# src/db/models/genre.entity.ts

import {
  Entity,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  OneToMany, PrimaryGeneratedColumn,
} from 'typeorm';
import BookGenre from './book-genre.entity';

@Entity()
export default class Genre {

  @PrimaryGeneratedColumn()
  id: number;

  @Column({name: 'genre_name'})
  name: string;

  @CreateDateColumn({name: 'created_at'})
  createdAt: Date;

  @UpdateDateColumn({name: 'updated_at'})
  updatedAt: Date;

  // Associations
  @OneToMany(() => BookGenre, bookGenre => bookGenre.book)
  bookConnection: Promise<BookGenre[]>;
}
# src/db/models/book-genre.entity.ts


import {
  Entity,
  PrimaryColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne, JoinColumn, PrimaryGeneratedColumn,
} from 'typeorm';
import Genre from './genre.entity';
import Book from './book.entity';

@Entity()
export default class BookGenre {

  @PrimaryGeneratedColumn()
  id: number;

  @PrimaryColumn({name: 'book_id'})
  bookId: number;

  @PrimaryColumn({name: 'genre_id'})
  genreId: number;

  @CreateDateColumn({name: 'created_at'})
  createdAt: Date;

  @UpdateDateColumn({name: 'updated_at'})
  updatedAt: Date;

  // Associations
  @ManyToOne(() => Book, book => book.genreConnection, {primary:
      true})
  @JoinColumn({name: 'book_id'})
  book: Book[];

  @ManyToOne(() => Genre,  genre => genre.bookConnection, {primary:
      true})
  @JoinColumn({name: 'genre_id'})
  genre: Genre[];
}

That’s All. Once you have all the entities setup, you are ready to CRUD records in the database using repositories and map to the above entity models.

TypeORM Repositories as a global module to query the database

Since we took the data mapper route, we need to define repositories for each of our entities, so we are going to create a global service repo.service.ts which can be accessed across the nest application to query any table or entity. Before that, we have to configure TypeORM in the main module, which in our case is app.module.ts.

src/app.module.ts

@Module({

  imports: [
     TypeOrmModule.forRoot(), 
     RepoModule   // Don't worry, we will create this next
  ],  // to use typeorm
  controllers: [AppController],  
  providers: [AppService],
})
export class AppModule {}

Next create two files, repo.service.ts and repo.module.ts

# src/repo.service.ts

import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import Author from './db/models/author.entity';
import Book from './db/models/book.entity';
import Genre from './db/models/genre.entity';
import BookGenre from './db/models/book-genre.entity';

@Injectable()
class RepoService {
  public constructor(
    @InjectRepository(Author) public readonly authorRepo: Repository<Author>,
    @InjectRepository(Book) public readonly bookRepo: Repository<Book>,
    @InjectRepository(Genre) public readonly genreRepo: Repository<Genre>,
    @InjectRepository(BookGenre) public readonly bookGenreRepo: Repository<BookGenre>,
  ) {}
}

export default RepoService;
# src/repo.module.ts

import { Global, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import RepoService from './repo.service';
import Author from './db/models/author.entity';
import Book from './db/models/book.entity';
import Genre from './db/models/genre.entity';
import BookGenre from './db/models/book-genre.entity';

@Global()
@Module({
  imports: [
    TypeOrmModule.forFeature([
      Author,
      Book,
      Genre,
      BookGenre,
    ]),
  ],
  providers: [RepoService],
  exports: [RepoService],
})
class RepoModule {

}
export default RepoModule;

Wow! We have just completed our setup for Typeorm, using data mapper and we have created migrations and models using typeorm one too many and typeorm many to many relationships.

Testing our first controller to see if we are able to query the database correctly

Open the app.service.ts file, we gonna use the existing function generated by nestjs CLI scaffolding to test our structure.

# src/app.service.ts

import { Injectable } from '@nestjs/common';
import RepoService from './repo.service';

@Injectable()
export class AppService {

  constructor(private readonly repoService: RepoService) {

  }

  async getHello(): Promise<string> { // querying database
    return `Total books are ${await this.repoService.bookRepo.count()}`;
  }
}
# src/app.controller.ts
......
  @Get()
  async getHello(): Promise<string> {
    return this.appService.getHello();
  }
.......

Once you have made changes to both app.service and app.controller file, you can run your project by ts-node src/main.ts. Once it runs, open the browser and you can see the following line

Total books are 0

Hurray! Your project is able to query the database. But that’s not all, We are going to employ the graphql integration into this project.

Integrating GraphQL with Nestjs and TypeORM

Since we already have installed the required packages above, in case you missed it, install the following package for graphql nestjs typeorm


yarn add type-graphql graphql dataloader @nestjs/graphql apollo-server-express
yarn add --dev @types/graphql 

Once the above packages are installed, we will modify our entities with type-graphql decorators, so the GraphQL types corresponding to entities are created inside our GraphQL schemas.

To create a type corresponding to the entity we will use @ObjectType() decorator from the type-graphql package. So you entities would look something like this

# src/db/models/author.entity.ts

......
@ObjectType()
@Entity({name: 'authors'})
export default class Author {

  @Field()
  @PrimaryGeneratedColumn()
  id: number;
.......

Once the type is exposed to the schema, we will start exposing our fields for the type using the @Field() decorator again from the type-graphql package.

Convert all your typeorm entities into GraphQL schemas.

Remember don’t annotate your associations with @Field(), we are going to deal with them separately.

Next, we have to import the GraphQL module in our app.module.ts so that NestJS will know about it. Change your app.module.ts file

......
import { GraphQLModule } from '@nestjs/graphql';

@Module({

  imports: [TypeOrmModule.forRoot(),
     RepoModule,
    GraphQLModule.forRoot({
      autoSchemaFile: 'schema.gql',
      playground: true,
    }),
  ],
........

GraphQL will generate the schema at the schema.gql file, in your root directory. You don’t have to worry about this file as this is maintained and updated by NestJS graphql as per the Schema, resolvers, and mutations.

Adding GraphQL TypeORM Resolvers which includes our mutations and queries.

Create a new directory inside src where resolvers for all the typeorm entities would be there


mkdir -p src/resolvers

In our resolvers directory, we will create our first resolver author.resolver.ts for the author entity.

In our resolver directory, we will create a directory to hold our graphql input types.


mkdir -p src/resolvers/input


Since we are working on the author resolver first. We will begin by creating the author.input.ts which will hold the input types for the author entity.

The first input type will be the one required for our create author mutation responsible for creating a new author record in our database.


#src/resolvers/input/author.input.ts

import { Field, InputType } from 'type-graphql';

@InputType()
class AuthorInput {
  @Field()
  readonly name: string;
}

export default AuthorInput;

As we have set up input for our resolver, we will start with our first resolver. Each resolver class is annotated with @Resolver decorator which is imported from the nestjs-graphql package (@nestjs/graphql).


#src/resolvers/author.resolver.ts

import { Resolver } from '@nestjs/graphql';

@Resolver()
class AuthorResolver {
}

After we have created the class for the resolver, we will add the repo service as a dependency in the constructor. As our RepoService is Global, so no need to worry about providing this service at the module level.


#src/resolvers/author.resolver.ts

import { Resolver } from '@nestjs/graphql';

@Resolver()
class AuthorResolver {
   constructor(private readonly repoService: RepoService) {}
}

To create a query or mutation the class field should be annotated with a @Query() or @Mutation resolver respectively again import from NestJS-GraphQL package (@nestjs/graphql).


#src/resolvers/author.resolver.ts

import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';

@Resolver()
class AuthorResolver {
   constructor(private readonly repoService: RepoService) {}

  @Query(() => [Author])
  public async authors(): Promise<Author[]> {
    return this.repoService.authorRepo.find();
  }
  @Query(() => Author, {nullable: true})
  public async author(@Args('id') id: number): Promise<Author> {
    return  this.repoService.authorRepo.findOne(id);
  }

  @Mutation(() => Author)
  public async createAuthor(@Args('data') input: AuthorInput): 
    Promise<Author> {
      const author = this.repoService.authorRepo.create({name: 
      input.name});
      return  this.repoService.authorRepo.save(author);
  }
}
export default AuthorResolver;

To create the above the mutations and queries in our GraphQL schema. We have to add all the resolvers to our main module which in this case is app.module.ts imports. To keep things simple we will create a separate array of resolvers, and use the ES6 spread operator to import it.

#src/app.module.ts

........
const graphQLImports = [
  AuthorResolver,
];

@Module({
  imports: [TypeOrmModule.forRoot(),
    RepoModule,
    ...graphQLImports,
    GraphQLModule.forRoot({
      autoSchemaFile: 'schema.gql',
      playground: true,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

The above resolver was an easy part, as it did not involve any associations to deal with. Though at the database level, the associations are handled by the typeorm. Each associative property needs to be resolved for the GraphQL.

Now we will begin writing out resolver for the Book entity. The input type for the Book will have two options. Either create the book for an existing author, by his id. Or create a new book and a new author for the same

  1. To connect to an existing author in the database by his ID
  2. To create a new author along with the book.

The input type for the book is shown below with the above functionality implemented.


#src/resolvers/input/book.input.ts

import { Field, InputType } from 'type-graphql';
import AuthorInput from './author.input';

@InputType()
class BookAuthorConnectInput {
  @Field()
  readonly id: number;
}

@InputType()
class BookAuthorInput {
  @Field({nullable: true})
  readonly connect: BookAuthorConnectInput;

  @Field({nullable: true})
  readonly create: AuthorInput;
}

@InputType()
class BookInput {
  @Field()
  readonly title: string;

  @Field()
  readonly author: BookAuthorInput;
}

export default BookInput;

According to the associations defined in our typeorm migrations and typeorm entities. Each book must have one author. And from our GraphQL playground while fetching records for books the author record for the book can also be fetched. To fetch the author record we need to resolve the property. And to do so we will use @ResolveProperty() decorator from the @nestjs/graphql package.

For using the @ResolveProperty() you must pass the entity to the @Resolve(), decorator.

The @ResolveProperty() will expect the property to resolve as a parameter. Or the corresponding function name should match the name of the property to resolve. And GraphQL parent objects to its corresponding function.


#src/resolver/book.resolver.ts
......
  @ResolveProperty()
  public async author(@Parent() parent): Promise<Author> {
    return this.repoService.authorRepo.findOne(parent.authorId);
  }
......

Now we will begin with the final block of our application the Genre resolver. Below is the input type for the Genre and GenreBook

#src/resolvers/input/genre.input.ts

import { Field, InputType } from 'type-graphql';

@InputType()
class GenreInput {
  @Field()
  readonly name: string;
}
export default GenreInput;


#src/resolvers/input/book-genre.input.ts
import { Field, InputType } from 'type-graphql';

@InputType()
class GenreBookInput {
  @Field()
  readonly genreId: number;
  @Field()
  readonly bookId: number;
}

export default GenreBookInput;

Now that is finished with the input types for the Genre and BookGenre, we will create resolver for the same.

#src/resolvers/genre.resolver.ts

import { Args, Mutation, Parent, Query, ResolveProperty, Resolver } from '@nestjs/graphql';
import RepoService from '../repo.service';
import Author from '../db/models/author.entity';
import Book from '../db/models/book.entity';
import BookInput from './input/book.input';
import Genre from '../db/models/genre.entity';
import GenreInput from './input/genre.input';
import BookGenre from '../db/models/book-genre.entity';

@Resolver(Genre)
class GenreResolver {

  constructor(private readonly repoService: RepoService) {}
  @Query(() => [Genre])
  public async genres(): Promise<Genre[]> {
    return this.repoService.genreRepo.find();
  }
  @Query(() => Genre, {nullable: true})
  public async genre(@Args('id') id: number): Promise<Genre> {
    return this.repoService.genreRepo.findOne(id);
  }

  @Mutation(() => Genre)
  public async createGenre(@Args('data') input: GenreInput): Promise<Genre> {
    const genre = new Genre();
    genre.name = input.name;
    return this.repoService.genreRepo.save(genre);
  }

  @ResolveProperty()
  public async book(@Parent() parent): Promise<Book[]> {
    const bookGenres = await this.repoService.bookGenreRepo.find({where: 
    {genreId: parent.id}, relations: ['book']});
    const books: Book[] = [];
    bookGenres.forEach(async bookGenre => books.push(await 
      bookGenre.book));
    return books;
  }
}

export default GenreResolver;
#src/resovlers/book-genre.resolver.ts

import { Args, Mutation, Parent, Query, ResolveProperty, Resolver } from '@nestjs/graphql';
import RepoService from '../repo.service';
import Author from '../db/models/author.entity';
import Book from '../db/models/book.entity';
import BookInput from './input/book.input';
import Genre from '../db/models/genre.entity';
import GenreInput from './input/genre.input';
import BookGenre from '../db/models/book-genre.entity';
import BookGenreInput from './input/book-genre.input';
import { Arg } from 'type-graphql';

@Resolver()
class BookGenreResolver {

  constructor(private readonly repoService: RepoService) {}
  @Mutation(() => BookGenre)
  public async createBookGenre(@Args('data') input: BookGenreInput): Promise<BookGenre> {
    const bookGenre = new BookGenre();
    const {bookId, genreId} = input;
    bookGenre.bookId = bookId;
    bookGenre.genreId = genreId;
    return this.repoService.bookGenreRepo.save(bookGenre);
  }

  @Query(() => [BookGenre])
  public async bookGenres(): Promise<BookGenre[]> {
    return this.repoService.bookGenreRepo.find();
  }

  @Query(() => BookGenre)
  public async bookGenre(@Arg('id') id: number): Promise<BookGenre> {
    return this.repoService.bookGenreRepo.findOne(id);
  }
}

export default BookGenreResolver;

The queries and mutations created can be run on the GraphQL playground, you can navigate to GraphQL playground on the route “/graphql”

The GraphQL playground.

The queries and mutations to run can be written on the left side of the graphql playground whose result is displayed on the right side after clicking the play button.

For your reference, below are some graphql queries and mutations with their results fetched from the playground.


// mutation to create an author
mutation {
  createAuthor(data: {
    name: "Sahil"
  }) {
    id
    name
    createdAt
    updatedAt
  }
}
Create Author GraphQL Mutation
Authors GraphQL Query.

The problem in the current approach.

The problem is not an obvious problem i.e our code is not going to blow up everything is going to work, the problem is an intuitive problem, using the dataloader we can make our application much more efficient. To illustrate the current problem we will fetch the books record using our genres query.

In the above query whenever the book is fetched it triggers the @ResolveProperty() method and the book records are fetched. i.e for n Genres n database queries will run and a total of n+1 queries will be executed. The database connections are the most expensive task we have. To resolve this problem we will use dataloaders.

Introduction To Dataloader

The Dataloader is a generic utility developed by facebook used to abstract request batching and caching.

The dataloader will wait for a single event loop cycle before it executes. And it calls back function and by the time an event loop cycle is completed, all the Book ids for the Book records to be fetched will have arrived. And instead of running n queries for n Genres we will run a single query. Which is a huge improvement over the previous approach

To use dataloader we need the dataloader package. Which in case you haven’t installed already can be installed by the command mentioned below.


yarn add dataloader

Now that our package is installed we will make the directory where our packages will sit.


mkdir -p src/db/loaders

Now that our directory for the resolver is created. We will write our loader to fetch Books based on the Genre Ids passed.

#src/db/loaders/books.loader.ts

import DataLoader = require('dataloader');
import Book from '../models/book.entity';
import { getRepository } from 'typeorm';
import BookGenre from '../models/book-genre.entity';

const batchBooks = async (genreIds: string[]) => {
  const bookGenres = await getRepository(BookGenre)
    .createQueryBuilder('bookGenres')
    .leftJoinAndSelect('bookGenres.book', 'book')
    .where('bookGenres.id IN(:...ids)', {ids: genreIds})
    .getMany();
  const genreIdToBooks: {[key: string]: Book[]} = {};
  bookGenres.forEach(bookGenre => {
    if (!genreIdToBooks[bookGenre.genreId]) {
      genreIdToBooks[bookGenre.genreId] = [(bookGenre as any).__book__];
    } else {
      genreIdToBooks[bookGenre.genreId].push((bookGenre as any).__book__);
    }
  });
  return genreIds.map(genreId => genreIdToBooks[genreId]);
};
const genreBooksLoader = () => new DataLoader(batchBooks);

export {
  genreBooksLoader,
};

The loaders are passed to each of our queries and mutations as a part of the context. Therefore, we will now begin writing our GraphQL context type.


mkdir -p src/types/
#src/types/graphql.types.ts

import { genreBooksLoader } from '../db/loaders/books.loader';

export interface IGraphQLContext {
  genreBooksLoader: ReturnType<typeof genreBooksLoader>;
}

Once the types for the GraphQL context created, we will create a GraphQL context. The context gets created in our GraphQL module present in the main app.module.ts

#src/app.module.ts

......
@Module({

  imports: [TypeOrmModule.forRoot(),
    RepoModule,
    ...graphQLImports,
    GraphQLModule.forRoot({
      autoSchemaFile: 'schema.gql',
      playground: true,
      context: {
        genreBooksLoader: genreBooksLoader(),
      },
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
......

Now that the loader is available to each of our queries and mutation via context. We can use it and modify our book to resolve property in our Genre resolver.

#src/resolvers/genre.resolver.ts

........
  @ResolveProperty()
  public async book(@Parent() parent, @Context() {genreBooksLoader}: 
  IGraphQLContext): Promise<Book[]> {
    return genreBooksLoader.load(parent.id);
  }

........

The author’s property is now resolve using the dataloader function exposed in our GraphQL context. And we have resolved the n+1 problem instead of running n database queries. The records will now be fetched using a single query. Thanks to Dataloader.

Also Learn TypeORM With NEST JS Basic Tutorial