Node.js REST, Mongo tips

  • In express library functions: post(), get() will stop the execution of code if you write return. It’s like in any other function in programming. keyword return will always stop the function execution.
  • When you write (res is the response callback function) res.end(), res.json(), res.send(), in other words when you end the response you cannot utilize res callback again it becomes irrelevant since you completed your restful service with a response. If you have any code after res.something() it will execute till you specify a return but res will not be available anymore. If you use it however, it will throw an error.
    Refer: Execute code after res.end() (StackOverflow)
  • You don’t need to return res.end(), json(), send() if you don’t have code which needs to execute after it.
  • If you don’t have anything to send to the Frontend side then use res.end() to complete the service action.
  • Use next function, specified at the end of restful service callback function:
    .get((req, res, next) => {action}

    to catch errors and forward them to the middleware:

    if (err) {
        return next(err);
    }

    the return next() will go to the already built in error handler and will result with a 500 XHR failed request on the Frontend. Also applies for catch() blocks, having next(err) will also result with Node.js built in error handler execution giving 500.

  • A Node.js mongoose query is not a JS Promise. They just represent a async operation which returns a then so that you can apply: query().then(res=>console.log(res));
    Refer: Mongoose async queries (StackOverflow)
    If you want a real instance of JavaScript Promise then put an exec() after your “fake” Mongoose query promise: query().exec().then(res=>console.log(res));
  • The default status for res.send(), res.json() is 200 thereby no need for res.status(200).send() or res.status(200).json();
  • In Mongoose findOneAndUpdate query
    User.findOneAndUpdate(findQuery, updateData, {
       upsert:true,
       useFindAndModify:false,
       new:true
    })
    upsert:true represents that if the record doesn’t exist a new one will be created/inserted
    useFindAndModify:false removes deprecation warning
    new:true gives the response of updated data, otherwise you get the data of the current findQuery record.
    I like to specify those parameters for each query so that I know what to expect from it.
  • ObjectId(userId) vs
    new ObjectId(userId) are the same, use whichever one you like but be consistent once you pick one.
  • Do not close your mongo database connection after terminating your query and then reopen upon querying database. You should have/define a pool of connections instead and closing it in Node.js process termination
    process.on(‘SIGINT’, mongo.mongoDisconnect).on(‘SIGTERM’, mongo.mongoDisconnect);
    Refer: Closing a Mongo connection (StackOverflow)
  • Do not use query.remove() for deleting data from the database it’s obsolete, use deleteOne, deleteMany instead.
  • For clearing the session and destroying the browser cookie use:
    req.sessionOptions.maxAge = 0;
    req.session=null;
    res.clearCookie(‘cookieName’);
    res.end(); 
    (I use it to logout the user)

Disable browser forward button in JavaScript

I’ve been trying to find some code recently to disable the forward button in the browser. Unfortunately, there has been no success with googling thereby I had to create a custom function to execute after the web-page has finished with content loading.

For those who are uninterested why this whole bunch of code had to be written and how the “button navigation disabling” actually works, just copy and paste the code into your app. The code had been tested in a manner of clicking and navigating back on a custom application, however, I urge you to test it extensively before going to production with it.

There are however 3 things which should be considered:

  • it won’t work on IE<10
  • it wont’ work using a hashlocation strategy (popular in react and angular frameworks)
  • if HTML5 history.replaceState() is used anywhere in your application then the code below might not work because of the replaceState canceling pushState() behaviour in the below code.

function for disabling the forward navigation button:


(function() {
  // function called after the DOM has loaded
  disableForwardButton();
})();

function disableForwardButton() {
  var flag, loop = false;
  window.addEventListener('popstate', function(event) {
    if (flag) {
      if (history.state != null && history.state.hasOwnProperty('page')) {
        loop = true;
        history.go(-1);
      } else {
        loop = false;
        history.go(-1);
      }
    } else {
      history.pushState({
          page: true
        },
        null,
        null
      );
    }
    flag = loop ? true : !flag;
  });

  window.onclick = function(event) {
    flag = false;
  };
}

Code Explanation:

In order to appropriately tackle the problem you first have to understand what is at your disposal and how these tools/commands work inside back navigation event (‘popstate’).

We’ll be using the following code:

  • history.go(-1), history.back() –> navigate backwards
    history.pushState(arg1, arg2, arg3) –> adding an extra entry element to our browser navigation array
  • ‘popstate’ event –> catches back, forward navigation click
    ‘onclick’ event –> catches any click event on the window object (needed to reset variables if the ‘popstate’ event occurred)

First, have in mind that there isn’t a switch off JavaScript code which would disable either the navigation forward button or the backwards button, therefore you have to take another approach which would prevent the app-user to click on the forward button.

The crucial thing to use here is the history.pushState() HTML 5 history API. Basically what it does (once used) is putting your current page at the end of the browser navigation array. In other words, if you execute this code in the ‘popstate’ event it would create another history and push it to the end of the array therefore disallowing the click of the forward button since you are on the last position (last item of the array). By doing this you haven’t disabled it at all you just appended an item to the array. Since you are now located at the end of the array then obviously you cannot go further (click forward).

To illustrate it a little bit more let’s create array states before the implementation of the pushState and after its implementation.

We’ll be using the following presumption of page history [page1, page2, page3]

  1.  let the current page we are on be page3. Once someone clicks the back button the ‘popstate’ event listener catches the event action and moves to page2
  2. Now again, let the current page be page3. With the pushState() function being implemented inside our ‘popstate’ listener the following transformation will occur inside our array [page1, page2, page2]. The page3 has been removed from the history and once landing on page 2 we pushed that exact page once more in the array and from that we’ve got no where else to go, our array doesn’t permit us to navigate forward like it did in the previous example. Because of the “no where going” the forward button in the browser is disabled or better to say inactive.

Once pushState() is implemented in our ‘popstate’ event we can now use the history.go(-1) function which helps us navigate to our previous page. The reason why we need it, is because pushState() will constantly push states (populate our browser page history) like the method name indicates therefore we will once be able to navigate back and after hitting the back button again we’ll be stuck on the current page. In order to evade this scenario we have to trigger a second back button click by using history.go(-1) or history.back(). The history.go(-1) will again trigger an event as we hit the back button and go through our code inside the popstate eventlistener. As you can see, we toggle between the history.go(-1) and pushState() in order to keep our forward button disabled and being able to navigate back.

The last thing which needs clarification is the code below:

if (history.state != null && history.state.hasOwnProperty('page')) {
  loop = true;
  history.go(-1);
}

Without this peace of code the forward button disabling would still work but you could run to a “never ending” back button navigation. This means that if you navigated back and have appended a vast number of elements inside your browser navigation array like for instance

[page0, page1, page2, page2, page2, page2, page2]

you would have to click the button numerous times in order to navigate to page1. Of-course, no one wants that, but such situation is very plausible and occurs often (the accumulation of pages in the array).

It happens because you might stop back navigating at some point (remember, pushState function executes at every back navigation button click) then click on some url within the webpage and then again navigate back going through page2 all the way to the starting page for example. Let’s say that you create this precise scenario:

[page0, page1, page2, page2, page2, page2, page2]

Having a bunch of same pages in the array and wanting to just jump to the target page which is page0. In this case we need to execute history.go(-1) until we reach the page1 (we cannot magically jump to it, we need to go through each and every element that we’ve created unwantedly) and then stop. this is done by setting the loop variable to true so that we don’t pushState() until we reach page1 where we pushState() again to disable the forward button.

That’s basically it. The HTML5 history API doesn’t allow you to explicitly look at their navigational array because of that we need to implement this dirty code to have our forward button disabled for the entire application.

If you notice a bug or have some uncertainties on how to implement the code, feel free to contact me.

Link to my stackoverflow answer

Angular 2 Jasmine unit testing (quick overview)

KEYWORDS:

  • describe: optional, describe the entire unit testing class
  • it: must include it when writing isolated unit test
  • async: tell the test framework to wait until the return promise or observable is completed before treating the test as completed. when all async operations are completed the next test (if exists) is able to start executing
  • beforeEach: for creating new instances for another test to start from the beginning
  • TestBed: creates components instance, configure module, simulate module
  • Access field/variable: fixture.componentInstance.some_variable_name OR if already instantiated then component.some_variable_name
  • detectChanges: only triggered when an property change occurs inside a .ts file
  • configureTestingModule: configures a “fake” module
  • toBe vs toEqual: toBe object(general) equality vs deep equality
  • fixture.whenStable().then(() => {}); executes after all async operations are executed/finished
  • tick() simulates the passage of time until all async operations above are finished. Must go with fakeAsync keyword, otherwise error will appear
  • fixture.whenStable() vs tick();
    They both do the same. tick() is more prudent to use because you have to give it (in the header of the test) a fakeAsync which means that everything is called synchronously inside the test. The code after the tick() method indicates that all code above has executed (async operations above) and that you can now proceed with testing the result of these above async operations.
    Fixture.whenStable() however can give a false positive if async() is omitted in the header of the test. Therefore the test will complete before fixture.whenStable executions.
  • A Spy is a feature of Jasmine which lets you take an existing class, function, object and mock it in such a way that you can control what gets returned from functions.


Configuring Test Module

...

innerHTML

    let fixture= TestBed.createComponent(AppComponent);
    let element1= fixture.debugElement.query(By.css(".heading")).nativeElement.textContent; //must include the point prefix (.)
    expect(element1).toContain("come")
});

 OR

  it ("test input innerHTML example", async()=>{
     let fixture= TestBed.createComponent(AppComponent);
     let element2= fixture.debugElement.nativeElement.querySelector(".heading");
     expect(element2.textContent).toContain("come");
});

input HTML tag

    it ("test input input-value attribute example", async()=>{
     let fixture= TestBed.createComponent(AppComponent);
     let element1= fixture.debugElement.nativeElement.querySelector("input");
     expect(element1.getAttribute("value")).toContain("som");
});

CSS style

    it ("test input input-value attribute example", async()=>{
     let fixture= TestBed.createComponent(AppComponent);
     let element1= fixture.debugElement.nativeElement.querySelector("input");
     expect(element1.getAttribute("value")).toContain("som");
});
    it ("test css style", async()=>{
     let fixture= TestBed.createComponent(AppComponent);
     let element1= fixture.debugElement.nativeElement.querySelector("h1");
     expect(element1.style.backgroundColor).toBe("blue"); // style attribute is the key for testing css
});

Class property testing


import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';

beforeEach(() => {
       TestBed.configureTestingModule({
           declarations: [AppComponent]
       });
     });

it('check title class property', async()=> {
  let fixture= TestBed.createComponent(AppComponent);
   expect(fixture.componentInstance.title).toBeDefined()
 });


Service testing

import { TestBed, async, inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { AppModule } from './app.module';
import { AppComponent } from './app.component'
import { MyServiceService } from './my-service.service'

beforeEach(() => {
let userServiceStub = {
isLoggedIn: true,
user: { name: 'Test User'}
};

//simulate module
TestBed.configureTestingModule({
declarations: [ AppComponent],
providers: [ {provide: MyServiceService, useValue: userServiceStub } ]
});
});

it('should test service object property value', inject([MyServiceService], (userService) => {
let fixture=TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(userService.user.name).toContain('se');

}));

Pipe testing

import { TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { AppModule } from './app.module';
import { AppComponent } from './app.component'
import { TryPipe} from './try.pipe'

it ("should check pipe content", async()=>{
    let piping= new TryPipe();  //create an instance of the pipe
    expect(piping.transform("")).toEqual("something"); //transform returns something initially
});

Directive testing

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { By } from '@angular/platform-browser';
import { FirstOneDirective } from './first-one.directive'
import { NO_ERRORS_SCHEMA }  from '@angular/core';

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [ AppComponent, FirstOneDirective ],
    schemas:      [ NO_ERRORS_SCHEMA ]
  }).createComponent(AppComponent);

});
it('should have skyblue css background, set from the directive', async()=> {
 //checking the code from the directive implementation
  const fixture=TestBed.createComponent(AppComponent);
  const de = fixture.debugElement.query(By.css('.nesto'));
  const bgColor = de.nativeElement.style.backgroundColor;
  console.log(de.nativeElement.textContent);
  expect(bgColor).toBe('cyan');
 });

([ngModel]) testing

  it('should pass twice, passes but because of two way data binding ngModel', async(() => {
    const fixture1 = TestBed.createComponent(ChangeRestApiComponent);
     fixture1.detectChanges();
     fixture1.whenStable().then(() => {
       let input_val = fixture1.debugElement.query(By.css('#first')).nativeElement;
       expect(input_val.getAttribute('value')).toBeNull();
       input_val.value = 'localhost';

       fixture1.detectChanges();
       input_val.dispatchEvent(new Event('input'));

       expect(fixture1.componentInstance.tempUrl).toContain('localhost');
     });
  }));

Check something to be false (not to contain a substring)

  it('should not contain full url paths, protocol e.g. http://', () => {
    component.array.forEach((item) => {
        expect(item.url.indexOf('http') === 1).toBe(false);
    });
  });

Checking html CHECKBOX element “checked” attribute

  it('check if checkbox checked attribute changed from default false to true', async() => {
    const input = fixture.debugElement.query(By.css('.className')).nativeElement;
    expect(component.testing).toBe(false);
    component.testing = true;
    fixture.detectChanges();
    expect(input.checked).toBe(true);
  });

Check value after BUTTON onClick event executes

it('check if on-button (click) event changes the value in the HTML', async() => {
     const div = fixture.debugElement.query(By.css('.clicking')).nativeElement;
     expect(component.clickMe).toBeUndefined();
     component.clickThisButton();
     fixture.detectChanges();
     expect(div.innerText).toEqual(component.clickMe);

  });

Check new INPUT value after change event executes

  it('change input value and check if change occured', async() => {
   const input = fixture.debugElement.query(By.css('.inputlast')).nativeElement;
   expect(input.value).toBe('undefined');
   component.changeMe = 'changed';
   fixture.detectChanges();
   expect(input.value).toEqual('changed');
  });

EventHandler(‘click’) testing

...

Routing testing

...

Local storage testing

...

JS quick tips

Quick theory

– JS uses camel case, lower than uppercase to write a function.
– JavaScript is a loosely typed language (no int, string, bool, char array value types…).
– Declare all variables at the top of the function.
– JavaScript uses the Unicode character set.
– JavaScript Types are Dynamic.
– All functions in JavaScript are objects.
– JavaScript functions parameters are value types.
– In JavaScript, arrays use numbered indexes, they do not support named indexes like in python, object support named indexes.
– In fact, in JavaScript, all functions have access to the scope “above” them.
– JavaScript supports nested functions. Nested functions have access to the scope “above” them. (closures)
– JS doesn’t have pointers (there are pointers but they are called references).
– Closures: when you first call the function then you just invoke the outer function, when you invoke the variable function then you actually call the inner function every time. Basically you need a „double“function call to get the closures to work, no magic.
– The difference between solo functions and and prototype functions is that prototype functions can be applied with a dot (.) where as solo function can not do that.
– Very important: the event queue cannot go into stack-overflow, only the stack can go in such state.
– No, JavaScript objects cannot have duplicate keys. The keys must all be unique. (this is important for example when removing duplicates)
–  Strict keyword– enhances the proper writing of JS. It prevents undeclared variables, it catches some common coding bloopers, throwing exceptions. it prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object). It prevents duplicate properties, eval becomes safer.
– NaN is a Number data type and appears when an arithmetic operation which had to be executed fails. Example: parsing a string to an integer which cannot be an integer when parsed, „abc“ to int.
– JS is asynchronous (non blocking) language
– JS is single threaded, one callstack, no parallel threads (multi-threads) only event loops
– The entire code inside the script block is the main function it doesn’t need a main function explicitly like in C#, Java, C etc.
– The event loop pushes the “result” from the queue to the stack if the stack is empty.

How does JS async work?

The function is pushed to the stack, the API is called for the function, the function executes and goes to the task queue. When the stack is empty the task queue pushes onto the single threaded stack.

Application of bitwise operators in JavaScript

First of all let’s revise what bitwise operators are and why you should comprehend them in 2017. Bitwise operators are operators that work on a bit or two bits (comparing them and giving a result based on the comparison) at a time.

AND ( & ) will  be 1 only if both of the bits are 1, otherwise it will be 0.
Example (all combinations): 1&1=1;  1&0=0;  0&1=0;  0&0=0;

OR ( | ) will be 1 if there is a 1 present when comparing two bits,
Example (all combinations): 1|1=1;  1|0=1;  0|1=1;  0|0=0;

XOR ( ^ ) is 1 only if one bit is 1 and the other is 0 no matter the order (1 XOR 0 =1)
(0 XOR 1=1)

NOT ( ~ ) if the bit is 0 it will go to 1 if it is 1 it will go to 0. In this case there is no comparison with other data. If you have an integer, let’s say 5 which is 0101 then the NOT will bring it to 1010.

To see the truth tables go to this website
Practical applications of bitwise operators (real life):
0X1 represents 1 in hexadecimal.


  • We check if the value is odd. If it is, the program returns true it ‘s not (if it is even) then the program returns false:


(value & 0x1) > 0

Explanation: Let’s say we have a value of 8 and on the other side we have 0x1. We convert them to binary numbers (that ‘s what the computer only understands at the most bottom level). We write the numbers one below the other and start the calculation from the most right bit to the most left bit (Refer to the and operator above)

1000
0001


0000

The result is 0000 which is 0 in denary (decimal ). Zero is not greater than zero so the expression returns false. Which means that the number is even.

JS code:

console.log((8 & 0x1) > 0)
  • Use them for data encryption (encryption is all about bitwise operators)

a = 1903349;
b = 4542345;
c = 5834533;
hash = a ^ b ^ c;

The numbers will be converted to binary and will be hashed (they will be transformed in some boolean XOR equivalent data)

Conclusion:

Bitwise operators are rarely used in JavaScript (as far as I’ve seen in 5 years of coding). I suppose interviewers use them for questions for future employees to see how deep the candidate went with their programming knowledge. Still, it is good to know them because once you see them and maybe have to do something with them you will have the basic knowledge in your head and solving the problem in front of you will require less time and frustration.

So, when doing operation with bitwise operators which are nothing else but boolean operations, always have in mind the true tables which are easy to understand and learn.

My opinion is, try to avoid them because your code looks incomprehensible to others who may in the future maintain your application. The more clearer you are the better for everyone else.

Changing border-color of HTML input element to red if an error occurs

On November the 7th a question was posted on SO where the OP wanted to change the border color of the input elements to red when both inputs didn’t match a condition.

I combined the JavaScript and a little bit of JQuery to solve this.

Here is the code:

var index_one;
var index_two;

    $('#Location, #LocationTo').change(function (e) {

        index_one = $("#Location")[0].selectedIndex;
        index_two = $("#LocationTo")[0].selectedIndex;
    });
    $("#submit").click(function () {
        if ($("#Location>option").eq(index_one).text() == $("#LocationTo>option").eq(index_two).text()) {
            $('#Location, #LocationTo').css("border-color", "red");
        } else {
            $('#Location, #LocationTo').css("border-color", "black");
        }
    });

As you can see, I first fetched the indexes of the selected items and after that I gave the index to the eq(index) jquery function in order to get the element as a object and then get the text via the .text() function. If the same options were selected in both input tags then the red border color will be displayed otherwise the black default color stays.

If you want to handle all the possible cases then add the following code:

else if($("#Location>option").eq(index_one).text() =="Please Select")
    {
        alert ("Select an option");
    }
      else if($("#LocationTo>option").eq(index_one).text() =="Please Select")
    {
        alert ("Select an option");
    }

Here is the fiddle to see the code in action: http://jsfiddle.net/eugensunic/eg8k4vL7/1/

Arrays, arrays and “arrays”

Arrays and objects are pretty similar in JS.  Let’s be sure that you distinguish those two.

Syntax for primitive array and storing values

One dimensional array

General syntax:

var name= [val,val,…val];

var elements = ["cube", "square", "triangle", "circle"];
alert(elements[0] + " and " +elements[2]);

Two dimensional array

General syntax:

(all rows and columns have to have the same length, see example):

var name= [[val,val,…val],…[val,val,…val]];

var numbers = 
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
alert(numbers[0][2]); //fetch the third element in the first row

Jagged array

General syntax (same as multidimensional but the all the rows and columns don’t have to be the same length:

var name= [[val,val,…val],…[val,val,…val]];

var numbers = 
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9, 5, 6]
];

//accessing jagged array option number 1
var second = numbers[2]; //storing the last row inside as a single row array
alert(second[4]); //accessing single row array “second” by index
//accessing jagged array as a multidimensional array option number 1
alert(numbers[2][4]);

Syntax for JSON array

Genenal syntax:

var name= [{prop_name:prop_val},…{prop_name:prop_val}];

var names= [
{
"name": "Ivan",
"lastname": "Maric",
},
{
"name": "John",
"lastname": "Taric",
}
];

//accessing JSON array:
alert(names[0].lastname); //accessing first lastname

Syntax for Object Literal

Object literal means that you instantly define the property inside the object and you give it the value.

General syntax:

var name= {prop_name:prop_val,…prop_name:prop_val};

var house =
{
address: "Road avenue 3",
height: "4",
width: "20",
furnished: false
};

//accessing Objects literal:
alert(house.furnished);