12/30/18

Is it complicate to write unit tests for your React app?

Not at all!
All you need is to install jest testing framework:

npm add --D jest babel-jest babel-preset-env babel-preset-react react-test-renderer
Add "test" script to "scripts" section in package.json file

  "scripts": {
    "start": "webpack-dev-server --open",
    "test": "jest",
Now you have the testing environment configured and running.
And you can start with adding some very simple unit test
You can create it on some file which has ".test" in its name - like example.test.js

test('adds 1 + 2 to equal 3', () => {
  expect(1 + 2).toBe(3);
});
After running
npm test
the result will be something like this
Now nobody can say about you that you never wrote a single test

12/11/18

Distructuring cheatsheet

Since I keep find myself forgot the ES6 destructuring syntax again and again I decided to publish this cheatsheet:

If you want to print one property of object:


const object = {name:'vasia'};
const {name} = object; 
console.log(`${name}`); // vasia 


If you want to this property to be named differently (bio)


const object = {name:'vasia'};
const {name: bio} = object; 

console.log(`${bio}`); // vasia 


If this property is inside other property (person)


const object ={person: {name:'vasia'}};
const {person:{name}} = object;

console.log(`${name}`); // vasia 
Hope this post will make me remember...

10/24/18

Kubernetes - Old replica sets remains after deployment

In this post i will write about annoying Kubernetes problem I managed to solve (at least I think it solved)
after long struggle.

So, here is the problem:

After running update-deployment-image command:

kubectl set image deployment/my-app my-app=gcr.io/my-cloud/my-app:new-image-tag 
The kubernetes showed that although the new image successfully updated, the old replicaset still remains:



Old replicates are all with 0 pods, but not removed.

Solution

The solution I found is to change the "selector" node in deployment configuration -
From:

  selector:
    matchLabels:
      app: my-app
      version: $SHORT_SHA
To

  selector:
    matchLabels:
      app: my-app
(Remove the "version" label)
And to add revisionHistoryLimit entry

spec:
  replicas: 2
  revisionHistoryLimit: 0
  selector:
    matchLabels:
      app: my-app

10/16/18

Make travis to push tags

What is travis you already know from the previous post. But what the kubernetes is?
According to the docs: "Kubernetes is a portable, extensible open-source platform for managing containerized workloads and services, that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem. Kubernetes services, support, and tools are widely available"
Get the long things shorter: kubernetes is the way to upload applications to google cloud, and also it can do lots of other things.

My Goal

So, my goal was: to get things published to cloud after all the testing stuff was done. (or after the travis finished)
Google cloud builder - another google cloud tool can be activated in response to push to some branch or in response to publishing some tag

In other words - my goal is to make travis to push tag after successful testing of every commit.

After Success Hook

Fortunately I found that travis has a after_success hook which I can utilise for my scenario:


language: node_js
node_js:
  - "9"
sudo: required
branches:
  except:
    - /^v.*\_.*/ 
dist: trusty
addons:
  chrome: stable
cache:
  directories:
  - $HOME/.npm
env:
  matrix:
    - MONGODB=3.6.6
before_install:
  - export GITHUBKEY=put-here-your-github-auth-token-key
install:
  ...
  ...
script:
  # run build script specified in package.json
  - npm run tslint
  - npm run test
  - npm run build
after_success:
  # CREATE GIT TAG
  - bash ./scripts/push_tag.sh

And here is the bash script code:

#!/bin/sh
git config --global user.email "koko@moko.com"
git config --global user.name "koko"
# Version key/value should be on his own line
PACKAGE_VERSION=$(cat package.json \
  | grep version \
  | head -1 \
  | awk -F: '{ print $2 }' \
  | sed 's/[",]//g' \
  | tr -d '[[:space:]]')

# should start cloud build only on prod test dev branches 
if [[ "${TRAVIS_BRANCH}" = prod || "${TRAVIS_BRANCH}" = test || "${TRAVIS_BRANCH}" = dev ]]; then
    export GIT_TAG="v${PACKAGE_VERSION}_${TRAVIS_BUILD_NUMBER}"
    echo "tag is ${GIT_TAG}"
    git tag $GIT_TAG -a -m "Generated tag from TravisCI build $TRAVIS_BUILD_NUMBER [ci skip]" $TRAVIS_BRANCH
    git push --tags https://$GITHUBKEY@github.com/oyrname/yourrepo
fi

Notice, that travis will react to the tag pushed by himself unless except entry configured properly:

branches:
  except:
    - /^v.*\_.*/

10/15/18

Making travis to test nodejs app

Tra... what?

May be you have noticed .travis.yml file in some of open source GitHub repos. Travis tool - is a CI tool for github. CI - means continuous integration, which in turn - means that after every change of code some checks will be run automatically. It can be unit test, can be code standard checks (like lint) or whatever you want to be checked.

My Situation

In my case - In our company we have some nodejs + typescript + mongo application which has mocha/chai unit tests (pretty common stack nowdays).
Here is basic travis configuration which runs tslint and unit tests


language: node_js
node_js:
  - "9"
sudo: required
dist: trusty
addons:
  chrome: stable
cache:
  directories:
  - $HOME/.npm
env:
  matrix:
    - MONGODB=3.6.6
install:
  - wget http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-${MONGODB}.tgz
  - tar xzf mongodb-linux-x86_64-${MONGODB}.tgz
  - ${PWD}/mongodb-linux-x86_64-${MONGODB}/bin/mongod --version
  - npm install
before_script:
  - mkdir ${PWD}/mongodb-linux-x86_64-${MONGODB}/data
  - ${PWD}/mongodb-linux-x86_64-${MONGODB}/bin/mongod --dbpath ${PWD}/mongodb-linux-x86_64-${MONGODB}/data --logpath ${PWD}/mongodb-linux-x86_64-${MONGODB}/mongodb.log --fork
script:
  # run build script specified in package.json
  - npm run tslint
  - npm run test
  - npm run build

Notice that mongo can be installed at testing machine travis creates each time when tests are run. Mongo is needed for run unit tests

8/31/18

magic of the dontenv

Recently i tried to solve the following problem: how to get react app to get backend Url from environment variable. The embarrassing truth is that until now my code was full of statements like this:

    fetch('http://localhost:8000/login', {
        method: "POST",
        credentials: 'include',
        headers: {
            "Content-Type": "application/json; charset=utf-8"
        },
        body: JSON.stringify( data )
    })
As you may notice - the url is hardcoded. The problem here is that this code will run only at developer environment where server running on 127.0.0.1 ("localhost") ip. But what about production environment where backend url can be http://yourappname.herokuapp.com ?

DONTENV

It appears the very cool solution for this problem is to use dotenv node plugin. Using it give us ability to define all environment specific variables in .nev file:

REACT_APP_API_HOST=http://localhost:8000
Now inside your react code you can access this variable this way:

 const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
 };
 fetch(`${process.env.REACT_APP_API_HOST}/login`, requestOptions)
        .then(handleResponse)

CREATE REACT APP

Create react app tool supports using .env files (so there is no need to install dotenv). You can create different .env files for different environments: like .env.local and .env.production.
By default - the "serve"(npm start) task will use "local", while "build" (npm run build) - will use production... Cool!

7/27/18

The .every method i discovered today

Looking on react-redux example i found the following line:


  if (user && requiredFields.every(key => user.hasOwnProperty(key))) {
    console.log('no need to call "fetch"')
    return null
  }

Notice the usage of "every" statement.

Every

So, what is the advantage of "every"?
consider you have the following array:


const arr = [{name:'yoyo', active:true}, {name:'momo', active:true}, {name:'bobo', active:false}]

How can you quickly know if all users are active?
So, you can loop through the array with "forEach", like this

let everybodyIsActie = true;
arr.forEach(user => {
   if(!user.active) { // if even one is not active
     everybodyIsActie = false;
   }
})
if(everybodyIsActie) {
 console.log('everybody dance now!')
}

But, much more awesome is to use "every" statement:

if(arr.every(user => user.active)) {
 console.log('everybody dance now!')
}

No need to use any variables
Unlike "forEach" (which doesnt returns enything) "every" returns true if every array item fills the condition
See you in my next post!

7/1/18

Playing With Css Grid - Part 2

One of most interesting features of CSSGrid - is
grid-template-areas feature. It makes you able to define layout areas and to associate the HTML element with specific layout parts.
Lets try to build following layout with css grid:


First lets divide the layout to the parts that will explain how much rows and columns each element will occupy:


.container{
  ...
  grid-template-areas:
      "nav header"
      "nav main"
      "nav footer";
}

Now We only need to 'explain' to each element - what the area it should belong to:

header{
  grid-area:header;
}

Clear and simple:

5/9/18

Squashing Commits With Vim (On VsCode)

When you about to do your first PR (pull request) it is important to know how to squash commits correctly.

Why? you may ask
- Well i know that you are probably good programmer and organized person, and you always use to give a second look before pushing something - to make sure the things are intact, but, somehow, sometimes, after pushing the commit (you checked before all and over!) - you find yourself looking at embarrassing typo you mysteriously missed while checking.

 So, what to do now? One way is to start all the thing again from the beginning (new branch, merge changes, new PR etc... ), but is it the only way?

 Fortunately (unlike real life) - there is a way to rewrite history - the rebase command!

 So, in case you found a typo - all you have to do is:
1. commit again (git commit -am "fixing typo")
2. run

git rebase -i HEAD~2
(because you want to squash 2 commits)
3. after running this command you will present with following screen: (in windows you need to press 'i' for enter into 'insert' mode)

4. modify the row of latest commit and replace 'pick' with 's'(squash)
5. (windows) press ESC(for exiting 'insert' mode)
6. (windows) type :wq to save changes and quit
8. in linux you just press CTRL + X



After selecting which commit to squash, you will present with screen where you can reformat the message of single commit you about to generate. You can just leave the message of original one and comment the others with '#'

7. run 

git push -f origin your-pr-branch-name

Now, look at your remote repo "commits" log: no traces of embarrassing typo, just one clean commit!

Imagine you could replay this way the world history and, for example, prevent the WW2... could be great, right?


Thats it,
Hope i helped someone in my situation

See you in my next post!

4/26/18

Playing With Css Grid

Css Grid feature is here for already long time, but until now i had no chance to experiment with it.
And i believe that one cannot claim he understand something to do with programming until he wrote some code.
So this time i will use codepen editor as playground for my experiments.

Css Grid - Get Started

First of all the grid must have a container - the wrapper element which CSS has display property set to "grid"

display: grid

All direct child elements inside container are called grid items

Layout

For practicing - lets start with building simple layout with header content and footer.
 Note: the "content" section must catch all free space between header and footer (which is little tricky)

For implement this layout lets set following HTML structure You may say it is too simple, but when you starting - i believe you have to be simple as possible (stupid simple)

<div class="container">
  <div class="header">header</div>
  <main>main</main>
  <div class="footer">footer</div>
</div

To make the "main" part catch all available space between header and footer - i will use grid-auto-rows feature
  grid-auto-rows: 60px auto 60px;

Thas it , see the codepen here:

4/22/18

Most Important Thing When Planning Application

As a programmer i'm not feeling in my own sphere when speaking a about application planning. It is not exactly my job - to plan. Programmer`s job is to implement the plans of product manager/designer/teamleader (and so far i'm only programmer).

Anyway, since planning is tightly connected  to programing, i think i must to have my own opinion on how those very important processes should be done correctly.  So here are my own conclusions on those topics

Point number one - when starting planning application it is very important to make clear (firstly for your self) - What this application should do , what problem it suppose solve? This point better to be formulated as short as possible

It is good to have the main application`s target as one sentence, for it will help to avoid following designs:

 (Motorcycle that initially planned to be a tank)

Also - to have a clear answer 'why i making this application' will make you understand if and when your goal is achived



 

4/8/18

Using New Angular6 Ng Update Feature

Everyone who using new angular knows that it depends on lot of packages - the @angular ones, rxjs, typescript and more. With so many dependencies- it might be hard job when trying to update, since some versions of some packages will not play with certain versions of other. (I call it dependency hell)



For solving this problem angular team added

ng update

command which should upgrade all the packages at once.
(Available from Angular CLI 1.7)

Experiment

Since it is interesting to play with new features, i decided to use this command for upgrading dependencies of one of my experimental projects. Its dependencies were like:

    "@angular/animations": "6.0.0-beta.7",
    "@angular/cdk": "6.0.0-beta.4",
    "@angular/common": "6.0.0-beta.7",
    "@angular/compiler": "6.0.0-beta.7",
    "@angular/core": "6.0.0-beta.7",
    "@angular/forms": "6.0.0-beta.7",
    "@angular/http": "6.0.0-beta.7",

And i expected that they will be upgraded to current 6.0.0-rc.3 version... After running command i got following message:
I guess that means the upgrade can be made only to stable version (not rc and not beta)

Well looks like angular guys still have some work to do...

3/20/18

Creating Javascript Router With Vanilla Javascript

What is router?
Router is a way to get different content in response to changes of url.
example:

That way it easy to memorize the url, and also you are able to navigate exact to product you need by the link (/vehicle/297 will lead you to SV650).
But what it means when speaking about JavaScript? Can JavaScript change the url without triggering full refresh of page?

Yes You Can

 It appears that javascript can change the url with HTML5 feature:

window.history.pushState("object or string", "sv650", "/sv650");



But How To Subscribe To Url Changes?

Yes, there is another HTML5 feature for it:
You can subscribe to 'pushstate' event:


window.addEventListener('popstate', (e) => {
  ...
});

Here is stackblitz project demonstrating routing in action

Summary

In this post you have learned that all 'Router' thing is actually very simple, and can be achieved with few pure javascript commands...
If you need more customizations like 'hash' Here is navigo vanilla javascript router...

2/21/18

How To Remove Property From Object Using ES6 Destructor

This trick i learned from Todd Motto`s grate ngrx tutorial:
Lets say you have javascript object like here:

  {
    "1": "koko",
    "2": "shoko"  
  }

And you need to remove only one property from it, say only the first one, which key is "1".
Yes, you can do it using old good "delete" command, but instead i recommend to take advantage of "ES6 destuctors" and spread
Destructors are way to set variables from existing object in one single command.
Spread command is for splitting the object (or array) properties to different variables.
By combining those to ES6 features we can do the trick:
Which is much more nice

2/13/18

What Is This "Tap" Thing In Rxjs?

In the bank of Jordan river, in the Moab land, Moses wished to explain his testament to Sons of Israel and that`s what is he said:
I'm looking at great angular-ngrx-material-starter repo of great guy named Tom Trajan
And here is the code of "auth.effects" file, where you can clear see the usage of "tap" operator:

  @Effect({ dispatch: false })
  login(): Observable {
    return this.actions$
      .ofType(AuthActionTypes.LOGIN)
      .pipe(
        tap(action => // <-- code="" here="" isauthenticated:="" see="" tap="" the="" thing="" this.localstorageservice.setitem="" true="">
So what is this "tap"(lettable operator) thing doing???

Documentation

When looking into rxjs docs you can see that "tap" is newer version of "do" operator.
Also you can see following sentence: invokes an action upon graceful or exceptional termination of the observable sequence.
That means - if you want something to be done regardless of outcome of observable you can do it with "tap"

Example

All the places in he code which only taking care of storing the payload(and not trying to modify the outcome of observable ) in the localstorage making usage if "tap":

  @Effect({ dispatch: false })
  persistTodos(): Observable {
    return this.actions$
      .ofType(TodosActionTypes.PERSIST)
      .pipe(
        tap((action: ActionTodosPersist) =>
          this.localStorageService.setItem(TODOS_KEY, action.payload.todos)
        )
      );
  }

When observable outcome is somehow modified - the "map" operator comes to the stage:

  @Effect()
  loadPizzas$ = this.actions$.ofType(pizzaActions.LOAD_PIZZAS).pipe(
    switchMap(() => {
      return this.pizzaService
        .getPizzas()
        .pipe(
          map(pizzas => new pizzaActions.LoadPizzasSuccess(pizzas)),
          catchError(error => of(new pizzaActions.LoadPizzasFail(error)))
        );
    })
  );

2/5/18

Most Important Skill In Your Career As A Programmer

Good morning to everyone of gs500coder blog readers!
As you can see i have published a lot of posts which could help you to improve your skills as a programmer, by learn some cool techniques in some programming domain (like CSS or Javascript)
But in this post i want to share some insight that became for me more and more clearer as my experience grows:
The most important skill for a programmer (even more important than advanced knowledge in his discipline) - is to be a good team player.

Team Player!? What do yo mean by that?

Yes. Like like in soccer game - one team member cannot win without collaboration of other team members (no matter how skilled he is), programmer must know how to work within a team. It may sound strange to some, but i found this to-be-a-good-teamplayer task even harder than any other programming tasks i do

Give Us Some Points Please

Since i not consider myself an expert at this field, here first (and last cause it is not easy)rule - i think a programmer should try to follow: Be a communicative person. (A person with whom other team members will feel convenient to talk, eat a lunch or share their thoughts ) That means also to be (no matter how frustrated you feel) friendly. Nobody likes angry people, Nobody likes to be blamed (no matter if it justified or not) Try to be optimistic man who gives to his mates/managers a feeling of hope
A good feeling should be a main measure of your success

Happiness Is Good

As far as i heard, there are scientific researches that prove: happier people is also healthier.
Thus - to be in a good relationship with everybody will not only benefit your work - it will benefit your health

2/1/18

Rxjs Pipe Operator (Nothing To Be Afraid Of)

Recently i noticed following code while going through Todd Motto NGRX tutorial:

  @Effect()
  loadPizzas$ = this.actions$.ofType(pizzaActions.LOAD_PIZZAS)
   .pipe(  // <=look here!!!
    switchMap(() => {
      return this.pizzaService
        .getPizzas()
        .pipe(
          map(pizzas => new pizzaActions.LoadPizzasSuccess(pizzas)),
          catchError(error => of(new pizzaActions.LoadPizzasFail(error)))
        );
    })
  );

Since i respect Todd Motto very much i decided to look what this pipe thing is about:
After pointing on "pipe" word and clicking "F12" key (in VSCode), that is what i got:
So this pipe is rxjs one of methods which exists on Observable object, like for example toPromise or subscribe
So what is it doing?
According to Rxjs documentation :

pipe method сan be used to compose the operators in similar manner to what you're used to with dot-chaining (shown below).

Thas all - compose various operators, like "switchMap" ,"map" or "catchError" which currently (in Rxjs 5.5) could be used as standalone operators instead of methods on an observable(pipeable)

Thats IT

1/13/18

Building A Dashboard Wiht Angular - Part3

Remember the dymanicComponent we started with?
Lets change it code so it will be able to display each of three widgets when a widget type passed as an "input" with its data:


import {Component, ViewContainerRef, ViewChild, Input, ComponentFactoryResolver} from '@angular/core';
import {VERSION} from '@angular/material';
import CompletedTasksComponent from './completed-tasks.component'; 
import EmailSubscriptionsComponent from './email-subscriptions.component';
import DailySalesComponent from './daily-sales.component'; 
@Component({
  selector: 'dynamic-cmp',
  template: `<div>
     here some dynamic stuff should happen
     <div #dynamicComponentContainer></div>  
  </div>`,
  entryComponents: [
    CompletedTasksComponent,
    EmailSubscriptionsComponent,
    DailySalesComponent
  ]
})
export class DynamicComponent { 
  componentRef:any;
  @ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;
  constructor(private resolver: ComponentFactoryResolver) {}
  @Input() set componentData(data: {component: any, data: any }) {
    if (!data) {
      return;
    }
    let factory = this.resolver.resolveComponentFactory(data.component);    
    this.componentRef = this.dynamicComponentContainer.createComponent(factory);
    this.componentRef.instance.data = data.data; // passing data to component through input

  } 
}

Now the component data and the component type passed to dymanicComponent as input:

    <mat-grid-list cols="3" rowHeight="1:1">
      <mat-grid-tile *ngFor="let data of componentData">
        <dynamic-cmp [componentData]="data"></dynamic-cmp>
      </mat-grid-tile>
    </mat-grid-list>

Please see my first stackblitz embedd here:

1/9/18

Building A Dashboard With Angular - Part2

More Dashborad

The material dashboad project used for me as inspiration, thus i will implemented 3 widgets using Chartist library:
Completed Tasks Chart


import {Component, Input, AfterViewInit} from '@angular/core';
declare const Chartist:any;
@Component({
  selector: 'completed-tasks',
  template: `
       <mat-card>
        <mat-card-title>
          Completed Tasks
        </mat-card-title>
        <mat-card-content>
            <div class="ct-chart" id="completedTasksChart"></div>
        </mat-card-content>
    
      </mat-card>
  `,
})
export default class CompletedTasksComponent implements  AfterViewInit {
  @Input() data :any; 
 
  ngAfterViewInit(){           
        const  optionsCompletedTasksChart = {
            lineSmooth: Chartist.Interpolation.cardinal({
                tension: 0
            }),
            low: 0,
            high: 1000, // creative tim: we recommend you to set the high sa the biggest value + something for a better look
            chartPadding: { top: 0, right: 0, bottom: 0, left: 0}
        }
                
        var completedTasksChart = new Chartist.Line('#completedTasksChart', this.data, optionsCompletedTasksChart);
        
  }
}

Daily Sales Chart

import {Component, Input, AfterViewInit} from '@angular/core';
declare const Chartist:any;
@Component({
  selector: 'completed-tasks',
  template: `
       <mat-card>
        <mat-card-title>
          Email Subscriptions
        </mat-card-title>
        <mat-card-content>
            <div class="ct-chart" id="dailySalesChart"></div>
        </mat-card-content>

      </mat-card>
  `,
})
export default class EmailSubscriptionsComponent implements  AfterViewInit {
  @Input() data :any;   

  ngAfterViewInit(){           
        const optionsDailySalesChart = {
            lineSmooth: Chartist.Interpolation.cardinal({
                tension: 0
            }),
            low: 0,
            high: 50, // creative tim: we recommend you to set the high sa the biggest value + something for a better look
            chartPadding: { top: 0, right: 0, bottom: 0, left: 0},
        }        
        
        var dailySalesChart = new Chartist.Line('#dailySalesChart', this.data, optionsDailySalesChart);        
  }
}

and
Email Subscriptions Chart

import {Component, Input, AfterViewInit} from '@angular/core';
declare const Chartist:any;
@Component({
  selector: 'completed-tasks',
  template: `
       <mat-card>
        <mat-card-title>
          Email Subscriptions
        </mat-card-title>
        <mat-card-content>
            <div class="ct-chart" id="emailsSubscriptionChart"></div>
        </mat-card-content>

      </mat-card>
  `,
})
export default class EmailSubscriptionsComponent implements  AfterViewInit {
  @Input() data :any;
   
  ngAfterViewInit(){
        const  optionsEmailsSubscriptionChart = {
            axisX: {
                showGrid: false
            },
            low: 0,
            high: 1000,
            chartPadding: { top: 0, right: 5, bottom: 0, left: 0}
        }
        
        
        var emailsSubscriptionChart = new Chartist.Bar('#emailsSubscriptionChart', this.data, optionsEmailsSubscriptionChart);    
  }
}

All the components getting their data through data input
Please see my first stackblitz embedd here:

1/4/18

Building A Dashboard With Angular - Part1

Why Dashboard?

Dashboards are very common thing in the world of wed apps, also it involves creation of dynamic components - thing i want to investigate.
Here i have gathered some useful links about Dynamic Components In Angular, so you can learn a lot of stuff about Dynamic Components:

Also this time i want to use stack blitz grate editor for demonstrating running code of samples, and for teaching myself how to use this great tool

Scenario

Lets say we wanna build some application which has user customized dashboard. Dashboard should display 3 kind of widgets as default, but use can decide which widgets will be displayed.

How To Create Dynamic Component

For creating dynamic component with current angular (version 5.2.0-beta.1 ) all you need to know about is ComponentFactoryResolver - angular factory that allows you to add components dynamically
Once you get ComponentFactoryResolver injected into constructor of dymanic component


constructor(private resolver: ComponentFactoryResolver) {}

You can add any component which registered inside entryComponents property Please see my first stackblitz embedd here:

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...