Validations in Full Stack Development

Full Stack Development, a quite tough to explain in a couple of lines. It takes ownership of the entire application from top to bottom. If you see a person as Full Stack Developer, he must be an all-rounder to develop an application from zero to high excellence. Full Stack Development includes 2 layers of architecture :

  1. Front-End Development (aka Client-Side / Presentation Layer)
  2. Back-End Development (aka Server-Side / Business Logic Layer)

Each Layer should have a data validations. Let’s dive in deeper,

Client-Side Validations

Validation takes place on the client side(web browser). It would be more frustrating to wait for the server response and re-enter the form that has nearly 100 inputs. So it is mainly for formatting data instantly and for the quick error recovery process.
Client-side validation gives the user feedback ASAP without having to wait for the server. It is an added topping, but not necessary. This will avoid the majority of validation issues and unnecessary processing from the server to perform data validations.

Pros:

  • Faster than Server-Side Validation
  • Better user experience can be provided by responding quickly(like invalid phone number, required fields,etc..)
  • Saves network bandwidth, traffic API calls

Cons:

  • Not Secure and useless if client-side scripts are disabled(javascript disabled)

Server-Side Validations

It is all about the data validation takes place on the server-side using the server-side scripting language. If you use server-side validation, you are developing a more secure application. Because client-side validations can be bypassed easily.

Let’s take a scenario. If a user is a technical guy/ a malicious user, he can pass invalid inputs through API testing tool or he can disable the javascript in client script or some malicious attack to skip client side validations. In these cases, validation will not happen. This may lead to incorrect entries, server downtime if any serious errors, etc, So we should verify on the server as well.

There are few libraries(eg., express-validator, etc) available to validate the inputs. Better, write a few code snippets for validations before continuing your business logic like

router.post(‘/api’, async(req, res) => {

 let isValidationPassed= await validateAndHandleInputs(req);

 if(isValidationPassed){

  //continue the business logics

 }

})

Pros:

  • More Secure than Client-Side Validation
  • Validation Techniques and Logics cannot be viewed/modified by the user.

Cons

  • Comparatively slower execution

References:

  1. https://www.smashingmagazine.com/2009/07/web-form-validation-best-practices-and-tutorials/
  2. https://medium.com/@davidpetri/server-and-client-side-validation-with-javascript-html-and-hapi-js-eccc779e448a
  3. http://net-informations.com/faq/asp/validation.htm
  4. https://surajdeshpande.wordpress.com/2013/08/10/difference-between-server-side-validation-and-client-side-validation/

Dropbox exordium

Hi Readers,

The idea about this blog is to cover the basic steps which we have to do, to integrate Dropbox with our application. The readers should have a minimal understanding of access_token, webhooks.

Recently I have started to do integration for my web application. The one which I integrated first was Dropbox

The Requirements are:

Fetch the dropbox files.

Get the corresponding redirect link.

Get the shared users for a file.

To integrate Dropbox into our Application:

  1. Create a Dropbox box app in the Dropbox developers site.
  2. After creation, use the ClientId and Client Secret of the app for authentication.

How to authenticate a user ??

The auth process can be done in two ways:

1. By creating a separate login.

2. By Click on a particular redirect link.

Note: The API URL should be encoded with client ID obtained.

Example:

https://www.dropbox.com/oauth2/authorize?response_type=code&client_id=” ”redirect_uri=””’

Redirect URI  →  The endpoint to receive the auth credentials.

After successful authentication, the auth credentials can be obtained in the redirect_uri.

Ohh, Wait! We are not close to getting the files.

Use the auth code, to get the Access_token for a user. Hit the following API endpoint with the auth code. https://api.dropboxapi.com/oauth2/token

Sample code:

let options = {

               url:https://api.dropboxapi.com/oauth2/token,

               qs: {
                  
                   'code': authCode,(code obtained by authentication)

                   'grant_type': 'authorization_code',

                   'client_id': '',

                   'client_secret': '',

                   'redirect_uri': ''

               },

               method: 'POST',

               json: true

           }

           return request_promise(options);

I have used request_promise to get the results. The redirect_uri should be same as the redirect URI provided during authentication.

Things to remember:

1. Redirect URI should be the same.

2. The Dropbox Client Id and Client Secret should be entered.

Hooray! We completed the process
Heaven, the dropbox access token will never expire.

The access token can be removed by only revoking.

How to drag the files from Dropbox to our App ??

The files  can be obtained by hitting the  following API endpoint :

https://api.dropboxapi.com/2/files/list_folder

The API returns the folders and files in a one-way tree. Nested files and folders can be obtained by setting the recursive field to true in the API hit.

Webhooks hit:

The Webhook hit can be configured in the Dropbox app which we created. Specify the corresponding webhooks URL. For authentication, the App will verify the URL by hitting with a challenge parameter. The app should be responded back with the challenge parameter.

Once the authentication is done, the webhooks hits the URL whenever the user of our app drops some files in their Dropbox.

References:

The dropbox also provides an API Explorer where the developers can view the live functioning of the API Endpoints

https://dropbox.github.io/dropbox-api-v2-explorer/

To know more about Dropbox  integration visit this link: https://www.dropbox.com/developers

 

 

Materialise your Angular App

As much as I love Angular, I also recognize that there are a few things that could make your Angular App look even more stunning without much effort! So, let’s go ahead and change your life in about 5 minutes by getting productive with Material Design using Angular Material in your Angular CLI app.

So, What Exactly is Angular Material?

Angular Material Design is a design language for web and mobile apps which was developed by Google in 2014. Material Design makes it easy for developers to customize their UI while still keeping a good-looking app interface that users are comfortable with and also you’ll get a well-organized format along with the flexibility to express your brand and style. For an example of Material Design, check out Airbnb, Gmail, and Houzz. These apps make the best use of Material Design to fit its many features into the limited mobile device. Going through the official Material design documentation is quite an experience. I recommend taking a look at the docs, but I will summarize it here.

Setup the Environment for Angular

To work with Angular, you will need Node.js and Angular CLI (Command Line Interface) installed in your development environment. Proceeding further, you can use the following command to set up a new Angular project.

ng new angular-material-app

Step 1: Install Angular Material and Cdk

Head over to your terminal, navigate inside your created Angular front-end application and then run the following commands to install Angular Material 6 and Angular 6 CDK.

npm install --save @angular/material @angular/cdk

Step 2: Install Angular Animations

In order to add enable support for animations in your Angular 6 front-end application, head back to your terminal and run the following command to install the Angular animations module and import the BrowserAnimationsModule and add it to the list of imports.

npm install --save @angular/animations

Step 3: Angular Material Theme

Angular Material comes prepackaged with several pre-built theme CSS files. To configure the basic theme, open the src/styles.css file and import any one of the available themes in Material Themes.

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

Step 4: Angular Material Gesture

Some components like Slide Toggle, Slider, and Tooltip rely on a library called HammerJS to capture touch gestures. So, you will need to install HammerJS and import it into our application.

npm install --save hammerjs

Step 5: Angular Material Icons (Optional)

If you want to use the mat-icon component with the official Material Design Icons, load the icon font in your index.html. For more information on using Material Icons, check out the Material icons guide.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

And yeah, Now you are good to go!

Note:  You can create an app-material module file for importing the angular material components and export them wherever necessary! Let’s write clean code and be a Better programmer!

What Will You Build with Angular Material?

After setting up the project structure and some dependencies, you will be able to start developing apps. You could try out some examples with the built-in components that are provided in Material docs. In this blog, to know about Angular material implementation, we will be implementing it with some small examples that play a major role in any webpage! The idea of this blog is to show how cool and easy it is to use Angular Material.

Example 1: Layout

The most widely used layout is cards. The most basic card needs only an <mat-card> element with some content. However, Angular Material provides a number of preset sections that you can use inside of an <mat-card>. For now, just copy the following code into your HTML file and you could witness a card display!

<mat-card> Simple Card</mat-card>

Example 2: Navigation

Next comes the navigation part of a webpage. <mat-menu> is a floating panel containing the list of options. By itself, the <mat-menu> element does not render anything. The menu is attached to and opened via application of the matMenuTriggerFor directive as follows.

<button mat-button [matMenuTriggerFor]="menu">Menu</button>
 <mat-menu #menu="matMenu">
   <button mat-menu-item>Item 1</button>
   <button mat-menu-item>Item 2</button>
 </mat-menu>

Example 3: Progress Bar

    “Boredom, according to psychologists, is merely lack of stimulation,the unfulfilled desire for satisfying activity. So what if we use the interface to give them that stimulation?”

~ Alice Kotlyarenko

Yeah! The UI progress bar will make you enjoy the wait! Angular Material made it easy to display a progress bar with customizable modes.

<mat-progress-bar mode="indeterminate"></mat-progress-bar>

Conclusion

I hope this blog has helped you understand how to use the power of Material Design in your app for a top-notch UI. For more information about Material Design in Angular 6, check out the official docs which contain ready-to-use templates. It’s a great place to learn about Angular. Thus Angular Material components create a beautiful application without investing too much time thinking about styles. Awesome, right?

Reference:

SwitchMap in rxjs

Let’s dive deep into switchMap with an example, so it helps as to understand what is it and when to use it.

Say we need to implement functionality for traffic signal which consists of 4 roads(A, B, C, D) meeting at a junction. The signals of these roads can be controlled either manually or automatically. The signal change is asynchronous(Observable- data stream).

const roadSignals = Observable.from(['Road SignalA', 'Road SignalB', 'Road SignalC', 'Road SignalD' ]);

roadSignals.subscribe((signal)=>console.log(signal));

Output: 

Road SignalA 

Road SignalB

Road SignalC

Road SignalD

Here comes the next part. We have to allow vehicles to pass through the junction when the signal is ON. Let’s try doing this with the help of the map. (Map -transform the items emitted by an Observable by applying a function to each item. Click here to learn about map )

roadSignals.pipe(

    .map((signal) => changeSignal(signal)),

    .map((allow) => allow.allowVehiclesObservable())

    ).subscribe((vehiclesObservable) => {

        vehiclesObservable.subscribe((vehicle) => console.log(vehicle))

    });

Here the vehicles in roads refer to an observable. So the output will be an Observable inside an Observable. We have to subscribe them in order to get vehicles individually.

In our case, allowVehiclesObservable is the outer Observable and vehiclesObservable is the inner Observable. We need to subscribe the vehiclesObservable(inner Observable) in order to get the vehicles individually. This method is called as FLATTENING.(subscribe inside a subscribe).

Come on let’s do flattening to get vehicles individually.

roadSignals.pipe(

    .map((signal) => changeSignal(signal)),

    .map((allow) => allow.allowVehiclesObservable())

    ).subscribe((vehiclesObservable) => {

        vehiclesObservable.subscribe((vehicle) => console.log(vehicle))

    });

Let a1, a2,.. b1, b2,.. be the vehicles in Road A, B, ..respectively.

Output :

a1

a2

a3

b1

b2

a4

Yes! Now we get vehicles individually. Flattening works:)

Wait a sec. What’s happening. Vehicles from Road A  as well as Road B is also moving. There are chances for accidents. After a few seconds, Signal C and Signal D will go ON. What if the vehicles from all the roads are moving.

 

Oh no. We should stop this. How to do this?

Whenever flattening is used we should use a Flattening Strategy.

  1. We need to store a subscription to the current vehiclesObservable subscription.
let subscription; (declare at top);

subscription = vehiclesObservable.subscribe(vehicle => console.log(vehicle));
  1. If new vehiclesObservable comes in we need to unsubscribe from the previous subscription before we subscribe to the new observable.
if(subscription) subscription.unsubscribe();

subscription = vehiclesObservable.subscribe(vehicle => console.log(vehicle));

Let’s apply the above steps:

let subscription;

roadSignals.pipe(

    map((signal) => changeSignal(signal)),

    map((allow) => allow.allowVehiclesObservable())

).subscribe((vehiclesObservable) => {

    if(subscription){

        subscription.unsubscribe();

    }

    subscription = vehiclesObservable.subscribe((vehicle) => console.log(vehicle))

    });

Output :

a1

a2

b1

b2

b3

c1

c2

SignalA comes first. Initially, the subscription is undefined.  RoadA-vehiclesObservable is stored in the subscription(local variable) and is subscribed. Vehicles from roadA start moving. When SignalB comes in, the subscription is defined (RoadA-vehiclesObservable). The if condition becomes true. Unsubscribe the existing subscription(RoadA-vehiclesObservable) and store the new subscription(RoadB-vehiclesObservable) to get vehicles from road B.No more vehicles from Road A..! When SignalC comes in, the existing subscription (RoadB-vehiclesObservable) is unsubscribed and new RoadC-vehicleObservable is subscribed.

As soon as the outer observable changes we kill the most recent observable and switch to new observable to replace it. Thus unsubscribing from the previous observable before subscribing to the new one is called as SWITCH Strategy.

Yes, we have achieved our desired result. But now,  the problem is the code became complex with observables, two subscribes, subscription, unsubscribe and all of these.

What to do?

Here comes switchMap for our rescue. We can replace the map and inner subscription with switchMap.

roadSignals.pipe(

    map((signal) => changeSignal(signal)),

    switchMap((allow) => allow.allowVehiclesObservable())

).subscribe((vehicle) => {

console.log(vehicle)

    });

Output :

Signal A

   vehicle a1

   vehicle a2

Signal B

   vehicle b1

   vehicle b2

Signal C

   vehicle c1

   vehicle c2

The main difference between switchMap and other flattening operators is the cancellation effect. On each emission, the previous inner observable (the result of the function you supplied) is canceled and the new observable is subscribed. You can remember this by the phrase switch to a new observable.

When to use and avoid switchMap?

switchMap can be used, when a new search is made, pending results are no longer needed; And should be avoided in scenarios where every request needs to complete, think writes to a database. switchMap could cancel a request if the source emits quickly enough.

References: