Uncategorized

differance between setTimeOut and setImmediate with real scenario

Hi friends, after getting to many question what are differance between setTimeOut and setImmediate. when to use setTimeOut and setImmediate. real time example/ scenarion for setTimeOut and setImmediate. now i am trying to explain with simple example, might be helpful for you all.

setTimeout:

setTimeout(,0) essentially means execute after all current functions in the present queue get executed.

setImmediate:

setImmediate is similar in this regard except that it doesn’t use queue of functions. It checks queue of I/O eventhandlers. If all I/O events in the current snapshot are processed, it executes the callback.

Lets explain setImmediate and setImmediate differance with a scenario.

have a look below code.



console.log('GAME LOADING START');
const timeoutScheduled = Date.now();
// If game not loaded in 3 sec show message. 
let timeOutAfter3Sec = setTimeout(() => {
    console.log("it seems like you are offline check your internet connectivity/ might be compatiblity issue.");
clearImmediate(allisGood);
}, 3000); // After checking compatibility and internet connectivity, if everythings fine show this message. let allisGood=setImmediate(() => { console.log('Everythings are fine enjoy game'); }); // Code to check internet connectivity and compatibility. let doCheck = function () { // Check start, you can change 1.5e10 value to simulate both scenaion. set less value to call allisGood and more for timeOutAfter3Sec for (var i = 0; i < 1.5e2; i++) { //checking } // Check end //Now calculate delay time, //if less than 3 sec(2900ms), clearTimeOut For showing offline/compatibility, in this case setImmediate will call and display message //if more than 3 sec(2900ms), setTimeOut will fire from event loop que, and will clear clearImmediate. const delay = Date.now() - timeoutScheduled; if (delay < 2900) { clearTimeout(timeOutAfter3Sec); } console.log('loop end time',Date.now(),'delay',delay); } // call check function. doCheck();

i hope this line of code helpful for you, if enjoyed please share on social channel might be helpful for other. if have any doubt can ask/comment.

Uncategorized

java script callback vs promise vs async-await explanation with real time scenario

​Hi, Today i want to show how to use callback, convert call back code to promise and promise code to async await.

Scenario: i want to cook food and then want to east. to cook food we have to follow some steps and all steps have some time

  • Preparation of materials to cook food take some time for example 2000ms
  • frying them take some time for example 1000ms
  • Cooking them them take some time for example 3000ms
  • Finally want to EAT in 500ms

Let us see. Here written JS Functions for them. and now see the output for the same

/** 
 * Problem with Java Script
*/
let preparation=function(){
    setTimeout(()=>{
        console.log(‘preparation’);
    },2000)    
}

let frying=function(){
    setTimeout(()=>{
        console.log(‘frying’);
    },1000)    
}

let cooking=function(){
    setTimeout(()=>{
        console.log(‘Cooking’)
    },3000)
}

let eating=function(){
    setTimeout(()=>{
        console.log(‘Eating’)
    },500)
}

preparation();
frying();
cooking();
eating();

Output:

Eating
frying
preparation
Cooking

Wow Before cooking of food we are eating here..

Don’t worry, We have Solutions, Solutions 1: Call Back

/** 
 * Solution 1: Call Back
*/

let preparation=function(frying){
    setTimeout(()=>{
        console.log(‘preparation’);
        frying(cooking);
    },2000)    
}

let frying=function(cooking){
    setTimeout(()=>{
        console.log(‘frying’);
        cooking(eating);
    },1000)    
}

let cooking=function(eating){
    setTimeout(()=>{
        console.log(‘Cooking’);
        eating();
    },3000)
}

let eating=function(){
    setTimeout(()=>{
        console.log(‘Eating’)
    },500)
}

preparation(frying);

Output as expected

preparation
frying
Cooking
Eating

Don’t worry, We have Solutions, Solutions 2: Promise in Java Script

/** 
 * Solution2: Promise
*/

let preparation=new Promise( function(resolve, reject){
    setTimeout(()=>{        
        resolve(‘preparation=>’);      
    },1000)    
})

let frying=new Promise( function(resolve, reject){
    setTimeout(()=>{
        resolve(‘frying=>’);      
    },1000)    
})

let cooking=new Promise(function(resolve, reject){
    setTimeout(()=>{
        resolve(‘Cooking=>’);
    },3000)
})

let eating=new Promise( function(resolve, reject){
    setTimeout(()=>{
        resolve(‘Eating=>’);
    },500)
})

Promise.all([
   preparation,
   frying,
   cooking,
   eating 
]).then(a=>{
    console.log(…a);    
});

Output as expected

preparation
frying
Cooking
Eating

Don’t worry, We have Solutions, Solutions 3: Async Await

/** 
 * Solution3: Async Await
*/

let preparation=new Promise( function(resolve, reject){
    setTimeout(()=>{        
        resolve(‘preparation=>’);      
    },2000)    
})

let frying=new Promise( function(resolve, reject){
    setTimeout(()=>{
        resolve(‘frying=>’);      
    },1000)    
})

let cooking=new Promise(function(resolve, reject){
    setTimeout(()=>{
        resolve(‘Cooking=>’);
    },3000)
})

let eating=new Promise( function(resolve, reject){
    setTimeout(()=>{
        resolve(‘Eating=>’);
    },500)
})

let start=async function(){
 console.log(await preparation);
 console.log(await frying);
 console.log(await cooking);
 console.log(await eating);
}
start();

Output as expected

preparation
frying
Cooking
Eating

if enjoyed please like and share with other, might be helpful for them

blog

factory-method-design-pattern

Factory Method Pattern

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.

The Factory Method Pattern is also known as Virtual Constructor.

Advantage of Factory Design Pattern

  • Factory Method Pattern allows the sub-classes to choose the type of objects to create.
  • It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That means the code interacts solely with the resultant interface or abstract class, so that it will work with any classes that implement that interface or that extends that abstract class.

Usage of Factory Design Pattern

  • When a class doesn’t know what sub-classes will be required to create
  • When a class wants that its sub-classes specify the objects to be created.
  • When the parent classes choose the creation of objects to its sub-classes.

UML for Factory Method Pattern

  • We are going to create a Plan abstract class and concrete classes that extends the Plan abstract class. A factory class GetPlanFactory is defined as a next step.
  • GenerateBill class will use GetPlanFactory to get a Plan object. It will pass information (DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN) to GetPalnFactory to get the type of object it needs.

blog

Abstract factory

Abstract Factory Pattern

Abstract Factory Pattern says that just define an interface or abstract class for creating families of related (or dependent) objects but without specifying their concrete sub-classes.That means Abstract Factory lets a class returns a factory of classes. So, this is the reason that Abstract Factory Pattern is one level higher than the Factory Pattern.

An Abstract Factory Pattern is also known as Kit.

Advantage of Abstract Factory Pattern

  • Abstract Factory Pattern isolates the client code from concrete (implementation) classes.
  • It eases the exchanging of object families.
  • It promotes consistency among objects.

Usage of Abstract Factory Pattern

  • When the system needs to be independent of how its object are created, composed, and represented.
  • When the family of related objects has to be used together, then this constraint needs to be enforced.
  • When you want to provide a library of objects that does not show implementations and only reveals interfaces.
  • When the system needs to be configured with one of a multiple family of objects.

UML for Abstract Factory Pattern

  • We are going to create a Bank interface and a Loan abstract class as well as their sub-classes.
  • Then we will create AbstractFactory class as next step.
  • Then after we will create concrete classes, BankFactory, and LoanFactory that will extends AbstractFactory class
  • After that, AbstractFactoryPatternExample class uses the FactoryCreator to get an object of AbstractFactory class.
  • See the diagram carefully which is given below:

 

blog

join two collections in mongodb using node js

Hi Friend Like Earlier Post today i would like to share my experience, Can we use Join in mongo DB like Sql?  Can We Use Where condition in mongo DB on Populated column?

Answer is YES. We can Use Join In Mongo DB and We can Use Condition on populated columns.

we can perform a left outer join by using the $lookup. The $lookup lets you specify which collection you want to join with the current collection, and which fields that should match. To apply condition on populated column use $unwind because look up return array and to access key need to use $unwind

Consider you have a “enquiries” collection and a “products” collection.
Enquiries collection have referance column for product.

Question is “want to accees Enquiry Data who enquire for product cotton shirt”

enquiries collection

[{
“_id”: “1”,
“enq_date”: “2019-06-27”,
“productid”: “1”
},{
“_id”: “1”,
“enq_date”: “2019-06-27”,
“productid”: “2”
},{
“_id”: “1”,
“enq_date”: “2019-06-27”,
“productid”: “1”
}]

products collection

[{
“_id”: “1”,
“product_name”: “cotton shirt”
},{
“_id”: “2”,
“product_name”: “cotton jeans”
}]

Querry is:

db.getCollection(‘enquiries’).aggregate([
{“$lookup”:{“from”:”products”,”localField”:”productid”,”foreignField”:”_id” ,”as” :”prod”}},
{“$unwind”:”$prod”},
{“$match”:{ “prod.product_name” : “cotton shirt”}},
])

blog

angular 8 new feature

What are New Features in angular 8?

Angular 8 have introduced some new feature and bug fixes.

Differential loading with modern browser

With new feature of angular 8 your apps will now be automagically more performant, when we create app build, two bundles will be created

  • Bundle for modern browsers that support ES2015+
  • Bundle for older browsers that only support the ES5 version of JavaScript.

The correct bundle will be loaded automatically by the browser.
This new feature results in the largest single performance improvement for Angular v8. Newer browsers will be able to load less code and load a much smaller amount of polyfills.

You don’t have to do anything special to benefit from differential loading, the ng build command with the –prod flag will take care of bundling everything

Dynamic imports for lazy routes

Get rid from typo error while lazy loading module. Now use the standard dynamic import syntax.

Old Syntax to add module in lazy load

{ path: ‘/customer’, loadChildren: ‘./customer/customer.module#CustomerModule’ }

 

Similar New Syntax will be

{ path: `/customer`, loadChildren: () => import(`./customer/customer.module`).then(m => m.CustomerModule) }

 

Ivy and Bazel New view rendering engine

New angular view engine Ivy and Bazel introduce in angular 8.

Bug Fixes

  • bazel: allow ts_library interop with list-typed inputs (#30600) (bf38df4)
  • bazel: Disable sandbox on Mac OS (#30460) (3de26a8)
  • bazel: ng test should run specific ts_web_test_suite (#30526) (8bc4da8)
  • core: remove deprecated TestBed.deprecatedOverrideProvider API (#30576) (5a46f94)
  • core: require ‘static’ flag on queries in typings (#30641) (c8af830)
  • core: temporarily remove @deprecated jsdoc tag for a TextBed.get overload (#30514) (561e01d), closes #29290#29905
  • router: type cast correctly for IE 11 bug breaking URL Unification when comparing objects (#30464) (32daa93)

 

blog

what are generic way to handle error in node js

what are generic way to handle error in nodejs?

If you want to implement good app your applications must have informative error messages to notify clients exactly why their request has failed. Errors might be caused either by the client (e.g., wrong input data) or by the server (e.g., a bug in the code). what are resolution’s of error. for a best practice API error response must have following things

  • Error Code
  •  Message
  • Description
  • Resolution

For example:

“error”: {

       “code”: 10001,

       “message”: “Invalid Email”,

       “description”: “please enter valid email id.”,

       “resolution”: “your email must have @.com/.in or domain name”

   }

Error Handling

Because of the asynchronous nature of Node.js and callback patterns, it’s not a trivial task to catch and log for future analysis the state in which errors happen. In the Chapter 17 of Pro Express.js, we cover the use of domains with Express.js apps. The use of domains for error handling in Express.js is a more advanced technique and, for most implementations right out of the box, framework’s built-in error handling might prove sufficient (along with custom error handling middleware).

The error handler spits out the error status (500, Internal Server Error), stack trace, and error message. It is enabled by this code only when the app is in development mode:

if (app.get(‘env’) === ‘development’) {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render(‘error’, {
message: err.message,
error: err
});
});
}

 

Tip: app.get(‘env’) is a convenient method for process.env.NODE_ENV; in other words, the preceding line can be rewritten with process.env.NODE_ENV === ‘development’

This makes sense because error handling is typically used across the whole application. Therefore, it’s best to implement it as middleware.

For custom error-handler implementations, the middleware is the same as any other except that it has one more parameter, error

// Main middleware
app.use(function(err, req, res, next) {
// Do logging and user-friendly error message display
console.error(err);
res.status(500).send();
});

We can use res.status(500).end() to achieve a similar result, because we’re not sending any data (e.g., an error message). It’s recommended to send at least a brief error message, because it will help the debugging process when problems occur. In fact, the response can be anything: JSON, text, a redirect to a static page, or something else.

app.use(function(err, req, res, next) {
// Do logging and user-friendly error message display
console.error(err);
res.status(500).send({status:500, message: ‘internal error’, type:’internal’});
})

Note: as good practice Always using proper HTTP response statuses such as
401, 400, 500, and so on, is recommended. Refer to List 9–1 for a quick reference.

Main HTTP Status Codes

  • 200- OK; Standard response for successful HTTP requests
  • 201- Created; Request has been fulfilled. New resource created
  • 204- No Content; Request processed. No content returned
  • 301- Moved Permanently; This and all future requests directed to the given URI
  • 304- Not Modified; Resource has not been modified since last requested
  • 400- Bad Request; Request cannot be fulfilled due to bad syntax
  • 401- Unauthorized; Authentication is possible, but has failed
  • 403- Forbidden; Server refuses to respond to request
  • 404- Not Found; Requested resource could not be found
  • 500- Internal Server Error; Generic error message when server fails
  • 501- Not Implemented; Server does not recognize method or lacks ability to fulfill
  • 503- Service Unavailable; Server is currently unavailable

 

blog

memento pattern

MEMENTO DESIGN PATTERN

The word ‘memento’ refers to an object kept as a reminder or souvenir of a person or event. Memento pattern is a behavioral pattern in GoF because it captures and externalize an object’s internal state so that the object can be restored to this state at a later time.

source: GoF

OVERVIEW

Memento, the class that represents a snapshot, simply contains the state of an object to be restored to an Originator. You and get and set state that a Memento encapsulates inside.

Originator, the class in which the current state is held. Originator has a member function that creates and return a Memento with the current state of the Originator stored into the Memento. Originator also has a member function that sets its current state with the state of a given Memento object. In other words, it can create snapshot (Memento), or restore the state to the given snapshot (Memento).

Caretaker object keeps and holds the Mementos, but never modify the Mementos. Caretaker class is responsible for the memento’s safekeeping. Usually, Caretaker encapsulates a list of Mementos that you can add more to the list, or get a Memento from the list.

MEMENTO CODE EXAMPLE

Memento class:

public class Memento {
private String state;

public Memento(String state){
this.state = state;
}

public String getState(){
return state;
}
}

Originator class:

public class Originator {
private String state;

public void setState(String state){
this.state = state;
}

public String getState(){
return state;
}

public Memento createMemento(){           // return a current snapshot
return new Memento(state);
}

public void setMemento(Memento Memento){  // restore from a snapshot
state = Memento.getState();
}
}

Caretaker class:

public class Caretaker {
private List<Memento> mementoList = new ArrayList<Memento>();

public void add(Memento state){
mementoList.add(state);
}

public Memento get(int index){
return mementoList.get(index);
}
}

main():

public class MementoPatternDemo {
public static void main(String[] args) {

Originator originator = new Originator();
Caretaker caretaker = new Caretaker();

originator.setState(“State #1”);
originator.setState(“State #2”);
caretaker.add(originator.createMemento());

originator.setState(“State #3”);
caretaker.add(originator.createMemento());

originator.setState(“State #4”);
System.out.println(“Current State: ” + originator.getState());

originator.setState(caretaker.get(0));
System.out.println(“First saved State: ” + originator.getState());
originator.setState(caretaker.get(1));
System.out.println(“Second saved State: ” + originator.getState());
}
}

Output:

Current State: State #4
First saved State: State #2
Second saved State: State #3

WHEN TO USE MEMENTO

  • Need an undo and restore mechanism.
  • Database rollback. To be able to rollback, have the Originator create a snapshot (memento) before performing an operation and thus in case of failure, the memento object would be used to restore the Originator to its previous state.
  • Want to simplify Originator code so it does not need to keep track of its previous state by moving such responsibility to the Caretaker code.

COMPARISON

memento vs command

  • Both can act as magic tokens to be passed around and invoked at a later time.
  • ​In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time.
  • Both can support muti-level undos.
  • Memento pattern’s capturing and restoring object state is more expensive then Command patterns for Undo/Redo functionality.
blog

singleton design pattern

Singleton design pattern

Motivation

Sometimes it’s important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.

The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Intent

  • Ensure that only one instance of a class is created.
  • Provide a global point of access to the object.

Implementation

The implementation involves a static member in the “Singleton” class, a private constructor and a static public method that returns a reference to the static member.

Singleton Implementation - UML Class Diagram

The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.

class Singleton
{
	private static Singleton instance;
	private Singleton()
	{
		...
	}

	public static synchronized Singleton getInstance()
	{
		if (instance == null)
			instance = new Singleton();

		return instance;
	}
	...
	public void doSomething()
	{
		...	
	}
}

You can notice in the above code that getInstance method ensures that only one instance of the class is created. The constructor should not be accessible from the outside of the class to ensure the only way of instantiating the class would be only through the getInstance method.

The getInstance method is used also to provide a global point of access to the object and it can be used in the following manner:

Singleton.getInstance().doSomething();

Applicability & Examples

According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used:

Example 1 – Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are usually implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 – Configuration Classes

The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.

Example 3 – Accessing resources in shared mode

It can be used in the design of an application that needs to work with the serial port. Let’s say that there are many classes in the application, working in an multi-threading environment, which needs to operate actions on the serial port. In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port.

Example 4 – Factories implemented as Singletons

Let’s assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multi threading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.

Specific problems and implementation

Thread-safe implementation for multi-threading use.

A robust singleton implementation should work in any conditions. This is why we need to ensure it works when multiple threads uses it. As seen in the previous examples singletons can be used specifically in multi-threaded application to make sure the reads/writes are synchronized.

Early instantiation using implementation with static field

In the following implementattion the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the instance member is declared static. This is why in we don’t need to synchronize any portion of the code in this case. The class is loaded once this guarantee the uniquity of the object.

Singleton – A simple example (java)

//Early instantiation using implementation with static field.
class Singleton
{
	private static Singleton instance = new Singleton();

	private Singleton()
	{
		System.out.println("Singleton(): Initializing Instance");
	}

	public static Singleton getInstance()
	{    
		return instance;
	}

	public void doSomething()
	{
		System.out.println("doSomething(): Singleton does something!");
	}
}

Protected constructor

It is possible to use a protected constructor to in order to permit the subclassing of the singeton. This techique has 2 drawbacks that makes singleton inheritance impractical:

  • First of all, if the constructor is protected, it means that the class can be instantiated by calling the constructor from another class in the same package. A possible solution to avoid it is to create a separate package for the singleton.
  • Second of all, in order to use the derived class all the getInstance calls should be changed in the existing code from Singleton.getInstance() to NewSingleton.getInstance().

Multiple singleton instances if classes loaded by different classloaders access a singleton.

If a class(same name, same package) is loaded by 2 diferent classloaders they represents 2 different clasess in memory.

Abstract Factory and Factory Methods implemented as singletons.

There are certain situations when the a factory should be unique. Having 2 factories might have undesired effects when objects are created. To ensure that a factory is unique it should be implemented as a singleton. By doing so we also avoid to instantiate the class before using it.

Hot Spot:

  • Multithreading – A special care should be taken when singleton has to be used in a multithreading application.
  • Serialization – When Singletons are implementing Serializable interface they have to implement readResolve method in order to avoid having 2 different objects.
  • Classloaders – If the Singleton class is loaded by 2 different class loaders we’ll have 2 different classes, one for each class loader.
  • Global Access Point represented by the class name – The singleton instance is obtained using the class name. At the first view this is an easy way to access it, but it is not very flexible. If we need to replace the Sigleton class, all the references in the code should be changed accordinglly.