NodeJS : Continuation Local Storage or Thread Local Storage?

Sometimes you need piece of data, most of the time request/response objects, between different events of a request where it is generally not accessible. Continuation Local Storage is a package to access the current express request/response object from a point where that is not readily accessible. 

Problem

Suppose you have a rest API (/users) that serves the user data. The handler of this API calls the service layer to get user data. The service layer calls your facade layer to get data from either directly from the database or from third party URL. After getting the data from different sources, facade layer combines the data and return to service layer that further returned to the actual API.

Now API layer accepts the cookie that contains some token to validate the request. The same token is required at facade layer. One way is to pass the token extracted from cookie at API layer to service layer that further will pass to facade layer.

In some cases, there can be other layers and events in which you need the same token or user data. Passing data, layers to layers is not a good practice and not a cleaner way.

So to sort the same problem Continuation Local Storage (CLS) comes into the picture.

What is Continuation Local Storage (CLS)?

Continuation Local Storage is a package to access the current express request/response object from a point where that is not readily accessible. It works like thread-local-storage in multithreading programming like java. As nodejs is single threaded it supports events/callbacks instead of multi-threads. And to achieve the same It uses the concept of **namespace**.

Node.js is asynchronous and uses an event loop to manage the asynchronicity, AsyncListener allows you to write software that can keep hold of information across callbacks.

What is Thread Local Storage (TLS)?

From Wikipedia

Thread Local storage (TLS) is a computer programming method that uses static or global memory local to a thread.

Setup

Let’s get started with Continuation Local Storage

1) Install the continuation-local-storage package

npm install continuation-local-storage --save

2) Create namespace that will hold the objects that we want to access at global level

let app = express();
let cls = require('continuation-local-storage');
let namespace = cls.createNamespace('com.domain');

3) Define middleware that will bind the request and response object to namespace

app.use((req, res, next) => {
   var nameSpace = cls.getNamespace('com.domain');
   // wrap the events from request and response
   nameSpace.bindEmitter(req);
   nameSpace.bindEmitter(res);
 
   // run middleware in the scope of the namespace that we have created
   nameSpace.run(() => {
       // set data to the namespace that we want to access in different events/callbacks
       namespace.set('data', "any_data");
       next();
   });
});

4) Now this data can be accessed at any layer. For demo, logging the data that was set in the namespace

//logger.ts

var getNamespace = require("continuation-local-storage").getNamespace;
let nameSpace = getNamespace("com.domain");
let data = nameSpace.get("any_data");
console.log("data : ", data);
Http Interceptor : Intercepting HTTP requests and response in Angular4

In the previous post, we have seen how to intercept the http request and response by extending Http class from @angular/http module.
To recall an http interceptor is

Interceptors are components that intercept calls and are used for logging, auditing, security and to implement authentication.

An Http interceptor is a middleware that can hijack http request/call before it reaches to the server and its response before it reaches the actual targeted function.

In Angular2 there was no cleaner way to implement interceptors, But Angular4 has an elegant and cleaner way to do this.  

What are we going to do?

We will create an interceptor class that will intercept the response object to check if the response status is 401 that is Unauthorized then the user will be redirected to the login page.

How?

To Create interceptor we will create a class HttpServiceInterceptor that will implement the HttpInterceptor interface from @angular/common/http module and register the same as providers in app.modules.ts. Following are simple steps to achieve the same

1) Create a class (HttpServiceInterceptor) and implement HttpInterceptor interface

@Injectable()
export class HttpServiceInterceptor implements HttpInterceptor { }

2) Provide definition to intercept method of HttpInterceptor interface

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
}

And the full code

// http-service-interceptor.ts
import { Injectable, Inject } from "@angular/core";
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from "@angular/common/http";
import { DOCUMENT } from "@angular/common";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/do";
@Injectable()
export class HttpServiceInterceptor implements HttpInterceptor {
    constructor( @Inject(DOCUMENT) private document: any) { }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).do(
            (event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    return event;
                }
            },
            (err) => {
                if (err instanceof HttpErrorResponse) {
                    if (err.status === 401) {
                        this.document.location.href =
                        `${this.document.location.protocol}//${this.document.location.hostname}:${this.document.location.port}/login`;
                    }
                }
            });
    }
}

3) Import HttpClientModule and HTTP_INTERCEPTORS from @angular/http/common module

import { HttpClientModule,HTTP_INTERCEPTORS } from "@angular/common/http"; // to make http request
import { HttpServiceInterceptor } from "../interceptors/http-service-interceptor"; // response interceptor

4) Make an entry for HttpClientModule in imports array

imports: [
  HttpClientModule
]

5) Add provider for HTTP_INTERCEPTORS and use the class (HttpServiceInterceptor) that we created for interception

providers: [{
   provide: HTTP_INTERCEPTORS,
   useClass: HttpServiceInterceptor,
   multi: true
}],

6) Then use HttpClient instead of http as your http service

import { HttpClient } from "@angular/common/http";

7) Inject in the constructor

constructor(private http: HttpClient) { }

That’s all folks!! Isn’t it easy? Oh yes..

Http Interceptor : Hijack http request and response in Angular 2

Interceptors are components that intercept calls and are used for logging, auditing, security and to implement authentication.

An Http interceptor is a middleware that can hijack http request/call before it reaches to the server and its response before it reaches the actual targeted function.

One of the most famous usages is to implement authentication. Interceptors are very useful when one wants to append a header in each request or want to manipulate the response before it reaches the actual calling party. It can also be used to show and hide loader on the screen based on http call.

Another use is to return json object as response as we use the .map method in every request’s response to return res.json, so the response can be hijacked or intercepted to do the same for all the requests.

Angular2  has not implemented the concept of interceptor but this can be done by extending the HTTP service. There are few steps that you need to follow to make this working.

1) Extend Http Service to provide your own functionality

// http-interceptor.ts
import { Injectable } from'@angular/core';
import { Http, XHRBackend, ConnectionBackend, RequestOptions, RequestOptionsArgs, Response, Headers, Request } from '@angular/http';
import{ Observable } from'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class HttpInterceptor extends Http {
     constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
         super(backend, defaultOptions);
     }
     /**
     * Error handler to handle is there is any error 
     * @param error 
     * @param caught
     * @returns {ErrorObservable}
     */
     private onCatch(error: any, caught: Observable<any>): Observable<any> {
         if (error.status === 500) {
             return Observable.throw(newError(error.status));
         }
         else if (error.status === 401) {
             return Observable.throw(newError(error.status));
         }
     }
      
      // interceptor method to intercept request and response
     get(url: string, options?: RequestOptionsArgs): Observable<any> {
         // options and url can be updated here to append new headers
          options.headers = {'Authorization' : 'token'};
         return super.get(url, options)
                     .catch(this.onCatch)
                     .map((res: Response) => {
                         // on sucess return res.json
                         return res.json();
                      }, (error: any) => {
                           console.log("On error :(");
                      })
                     .finally(() => {
                         console.log('After the requset has been completed :)');
                     });
     }
}

2) Add this extended service in app.module.ts

providers: [{
    provide: HttpInterceptor,
    useFactory: httpInterceptor,
    deps: [XHRBackend, RequestOptions]
}]

Where httpInterceptor is an exported function that returns the new instance of extended HttpInterceptor class.

// to return an instance of HttpInterceptor class
export function httpInterceptor (backend: XHRBackend, defaultOptions: RequestOptions) {
    return new HttpInterceptor(backend, defaultOptions);
}

Instead of creating this function one can directly use the function in provider section but this creates problem while bundling the project. The following error can be encountered

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference
to an exported function (position 45:5 in the original .ts file), resolving symbol AppModule in D:/SK/Study/Material/MDCAngular/src/app/app.module.ts

Now to use this extended class inject the implementation of HttpInterceptor class like this where you want to inject http service

constructor (private http: HttpInterceptor) { }

Further Reading

http://array151.com/blog/http-interceptor-angular4/

References

https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462

React Native : Setup Android Environment on Windows

React Native is a framework for Javascript to create native mobile apps. Facebook announced this framework in 2015 to create iOS and Android apps using same javascript codebase instead of writing the different code for different platforms. It uses the same building blocks as iOS and Android apps use to build apps, with react architecture and javascript.

React Native Setup

Setting react native on windows machine is very easy. There are few steps to follow

1) Install JDK7 or newer version of Java from official website.

2) Install NodeJS

3) Install Android SDK

4) Set environment variable for JAVA_HOME and ANDROID_HOME

5) Install React Native CLI globally using the command

npm install react-native-cli –g

This will provide you a utility/command react-native to manage and configure projects.

6) Create React Native project using command

react-native init <project-name>

React Native Setup

If everything gets fine you will see the following output on console

added 319 packages and updated 2 packages in 63.072s
To run your app on iOS:
   cd D:\PROJECTS\Android\MyPU
   react-native run-ios
   - or -
   Open ios\MyPU.xcodeproj in Xcode
   Hit the Run button
To run your app on Android:
   cd D:\PROJECTS\Android\MyPU
   Have an Android emulator running (quickest way to get started), or a device connected
   react-native run-android

In the above snippet MyPU is the project name. You can run the build on the virtual machine by configuring it in android studio but better to run it on physical device as running virtual machine is very slow process. To run build on physical device follow the steps :

     *) Connect your device to machine (Android Device)

      *) On developer option from Setting -> Developer options

7) Now change the directory to created project. In our case MyPU. Use cd command from terminal to change the directory to MyPU

 cd MyPU

8) Run the following command to run android build

react-native run-android

A react packager will be started to load dependency graph as a new process and it will take few minutes to generate android build. If build process is successful then you will see on the command prompt

BUILD SUCCESSFUL
Total time: 2 mins 47.906 secs
'adb' is not recognized as an internal or external command,
operable program or batch file.
Starting the app (D:\SOFTWARE\LANGUAGE\ANDRIOD\AndroidSDK1/platform-tools/adb sh
ell am start -n com.mypu/com.mypu.MainActivity...
Starting: Intent { cmp=com.mypu/.MainActivity }

And app will be visible on your connected physical device 🙂

React Native App on Android Device

Issue 1 : Unable to load script

There can be error on your connect device showing

Unable to load script from assets “index.android.bundle”

Unable to Load Script

To solve this problem

1) Stop the existing running command by pressing Ctrl + C.

2) Create the folder assets under android/app/src/main/assets

3) Now you need to change the android bundle output using the following command

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

4) Now run the command again to run android build

react-native run-android

Issue 2 : SDK Version Mismatch

If you have Android SDK version mismatch in build.gradle and the one installed in your system, then the following error will be shown your console

FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring project ':app'.
> Failed to find Build Tools revision 23.0.1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED

Solution

Open Project-Name/android/app/build.gradle file and under 

android {
  compileSdkVersion 25
  buildToolsVersion "25.0.2"
 defaultConfig {
   applicationId "com.demorn"
   minSdkVersion 16
   targetSdkVersion 22
   versionCode 1
   versionName "1.0"
   ndk {
     abiFilters "armeabi-v7a", "x86"
   }
 }

update the compileSdkVersion and buildToolsVersion  to the version that you have installed under Android/sdk/build-tools.

Bonus : Directory Structure of React Native App

Directory structure is a way how you construct or bind your code and into folders. Even though this does not matter in the initial phase of app but it is the best practice to use a simple directory structure of app for better understanding. You can follow any directory structure to construct your app. But personally I use this structure to make my apps.

React Native : Android weds iOS

As javascript is getting so popular and powerful language, many of the frameworks have been created to ease the work of developer and development. It is now being used on the server side with the invent of NodeJS platform.

What is React Native

Like other frameworks, React Native is also a framework for Javascript to create native mobile apps. Facebook announced this framework in 2015 to create iOS and Android apps using same javascript codebase instead of writing the different code for different platforms. It uses the same building blocks as iOS and Android apps use to build apps, with react architecture and javascript. Here is the official website to learn basic concepts.

Power of React Native

With RN you don’t just create the HTML 5 applications or hybrid apps, RN gives you the power to create actual mobile apps using Javascript.

Thousands of apps are created using RN including the top most used apps like
1) Instagram
2) Facebook
3) Skype
4) Tesla
5) SoundCloud Pulse

Here is the list of all apps created using React-Native.

    React Native Setup >> Next

HTML : Properties and Attributes

Properties and attributes of a DOM element seem same but there is a difference between these two terms. When writing HTML source code, attributes are defined in HTML elements. Browser parses HTML code and a corresponding DOM node is created. This DOM node is an object, and therefore it has properties.

For instance, the HTML element:

<input type="text" value="name">

has 2 attributes.

When above HTML code is parsed by browser a corresponding HTMLInutElement object is created with different properties like accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children etc.

Properties are the properties of that object, and attributes are the elements of the attributes property of that object. When a DOM node is created for a given HTML element, many of its properties relate to attributes with the same or similar names, but it’s not a one-to-one relationship.

For instance, the HTML element:

<input id="elementId" type="text" value="name">

the corresponding DOM node will have id, value and type properties :

1) The id property is a reflected property for the id. Changes in the id property will get reflected to id attribute.

2) Value property doesn’t reflect the value instead, it’s the current value of the input. So if user types “Array151” in input box then value will return Array151 but the

Input.getAttribute('value');

will return the value attribute that is name.

3) The type property is a reflected property for the type. Changes in the type property will get reflected to type attribute, but type isn’t a pure reflected property as it is limited to valid types of an input that is some known values.

For instance. If we have an element with type “abc

<input type="abc">

then the

Input.getAttribute("type") 

gives you “abc” 

but the

Input.type 

gives you “text“.

The value property reflects the current text-content inside the input box, whereas the value attribute contains the initial text-content of the value attribute from the HTML source code.

In nutshell, most of  properties are directly reflection of HTML attributes and some are direct reflections with slightly-different names (htmlFor reflects the for attribute, className reflects the class attribute), many that reflect their attribute but with restrictions/modifications (src, href, disabled, multiple), and so on. For more on this go through the spec

Reference

https://stackoverflow.com/questions/6003819/properties-and-attributes-in-html

en_USEnglish
en_USEnglish