GraphQL

I’ve started learning GraphQL and decided to share some information that I find useful.

GraphQL is a query language to retrieve data from the server.

Unlike REST queries, GraphQL is “smart”. Main benefit is that, instead of many REST nodes, we only have one smart node, that can provide us with the exact information we need.

Basic GraphQL queries

People commonly call everything that hits your GraphQL API server a “query”. But there are a lot of things mixed in there. What do we call a unit of work we’re asking the server to do? It could be a query, a mutation, or a subscription. 

GraphQL Operation.JPG

Selection sets

GraphQL Selection Set.JPG

  • Selection set: A set of fields requested in an operation, or nested within another field. A GraphQL query must contain a selection set on any field that returns an object type, and selection sets are not allowed on fields that return scalar types, such as Int or String.

Source: https://dev-blog.apollodata.com/the-anatomy-of-a-graphql-query-6dffa9e9e747

Advertisements

Check if the JSP file on app server is latest

Sometimes deploying the app may not refresh jsp files on app server. So you might see in browser that app has old logic. To confirm that app server doesn’t have latest files go to app server. Typically:

$ssh -A appServer

Then switch to root

$ sudo su –

Then navigate to the folder

$cd /opt/tomcat/webapps/ROOT/WEB-INF/views/

then open the jsp file and see the content

If the file is old, just re-deploy via Jenkins

 

Living in the Singapore, cost of living, finding the room or apartment

It’s been almost 9 months I’ve worked in Singapore. I will be sharing some information for those whom can benefit from it.

The average cost that I spend per months goes as follow, all values are in SGD:

  1. Rent – 750 for common room(need to pay deposit 1 month when starting the contract )
  2. Transport(bus and mrt) – 70-80
  3. Communications(Singtel) – 70
  4. Food(fruits, lunch, dinner, snacks etc) – 500

Total: ~1400

The best way to find the room or apartment is to ask the agent to find it for you(you will need to pay the agent fee which equates to the half of the rent(for both room or apartment)). I find the agents from  http://www.orangetee.com most useful(can recommend to email to george.kyaw@orangetee.com please note he only handles the apartment rentals)

If you don’t want to pay agent fee, then your best chance is to go to easyroommate.com and put your add there.

Another places where to find the room/apartment is https://www.gumtree.sg/, http://www.propertyguru.com.sg , nestia.com (in no particular order). Or facebook groups.

How to merge the previous branch to current one using SmartGit

In Smartgit, click Merge, then click branches. Uncheck all. Then check the Origin->Previous sprint – > Merge to Working Tree.

Then see if there is conflicts. If there is one, you can either right click ->Resolve then choose our file or their file. 2nd way is to open conflict by clicking twice on the file, then clicking on the arrow to accept the correct code.

Then Commit->Push

More about JavaScript closures

From my understanding closures is extremely important concept in JavaScript. Let’s learn it in details:

Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions ‘remember’ the environment in which they were created.

Lexical Scooping

Lexical scooping is a type of closure.

function init() {
var name = “Mozilla”; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert (name); // displayName() uses variable declared in the parent function
}
displayName();
}
init();

Here you can notice that init() has function inside. Then when init is called, that function is called too.

Git: how to use cherry pick using smartgit

If you have have multiple git branches and you have pushed your code to branch x, but you also want it to be available on other branch too ex.: branch Y, then perform following steps:

  1. Checkout the branch Y, the place where you want to push your code
  2. Then from toolbar above, Branch->Cherry Pick
  3. Click Branches, and un-select the Head. Then select the branch X. Choose the commit you want to add to branch Y.
  4. Select and press Cherry pick and commit
  5. then press Push
  6. Done

Now branch Y has commit from branch X.

10 JavaScript concepts

original link: http://www.javaworld.com/article/3196070/application-development/10-javascript-concepts-nodejs-programmers-must-master.html

1. Immediately invoked function expressions

(function(){
                        // all your code here
                        // ...
            })();

this will immediatlly execute the code

2. Closures

A closure in JavaScript is an inner function that has access to its outer function’s scope, even after the outer function has returned control. A closure makes the variables of the inner function private

var count = (function () {
            var _counter = 0;
            return function () {return _counter += 1;}
})();
count();
count();
count();
// the counter is now 3

3. Prototypes

Every JavaScript function has a prototype property that is used to attach properties and methods. This property is not enumerable. It allows the developer to attach methods or member functions to its objects. JavaScript supports inheritance only through the prototype property. In case of an inherited object, the prototype property points to the object’s parent. A common approach to attach methods to a function is to use prototypes as shown below:

function Rectangle(x, y) {
            this._length = x;
            this._breadth = y;
}

Rectangle.prototype.getDimensions = function () {
            return { length : this._length, breadth : this._breadth };
};

Rectangle.prototype.setDimensions = function (len, bred) {
            this._length = len;
            this._breadth = bred;
};

4. Private properties, using closures

JavaScript lets you define private properties by special technique. By default js don’t provide any private property. We use _ on the variable name as convention to let everyone know that this is private variable.

Defining private properties using closures will help you solve this problem. The member functions that need access to private properties should be defined on the object itself. You can make private properties using closures as shown below:

function Rectangle(_length, _breadth) {
            this.getDimensions = function () {
            return { length : _length, breadth : _breadth };
            };

            this.setDimension = function (len,bred) {
            _length = len;
            _breadth = bred
            };
}

5. The Module pattern

The Module pattern is the most frequently used design pattern in JavaScript for achieving loosely coupled, well-structured code. It allows you to create public and private access levels. One way to achieve a Module pattern is shown below:

var Direction = (function() {
  var _direction = 'forward'

  var changeDirection = function(d) {
            _direction = d;
  }

  return {
            setDirection: function(d) {
            changeDirection(d);
            console.log(_direction);
            }
  };

})();

Direction.setDirection('backward');   // Outputs: 'backward'
console.log(Direction._direction);

6. Hoisting

JavaScript moves variables and function declarations to the top of their scope before code execution. This is called hoisting. Regardless of where you place the declaration of functions and variables in your code, they are moved to the top of their scope by the interpreter.

The priority is given below from higher to lower:

  • Variable assignment
  • Function declaration
  • Variable declarations

x = 5; // Assign 5 to x

elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x;                     // Display x in the element

var x; // Declare x

Declare Your Variables At the Top !

7. Currying

A technique using partial evaluation. Currying refers to the process of transforming a function with multiple arity into the same function with less arity. The curried effect is achieved by binding some of the arguments to the first function invoke, so that those values are fixed for the next invocation.

var myFirstCurry = function(word) {
  return function(user) {
            return [word , ", " , user].join("");
  };
};

var HelloUser = myFirstCurry("Hello");
HelloUser("Rahul"); // Output: "Hello, Rahul"

The original curried function can be called directly by passing each of the parameters in a separate set of parentheses one after the other as shown below:

myFirstCurry("Hey, wassup!")("Rahul"); // Output: "Hey, wassup!, Rahul"

8. The apply, call, and bind methods

It’s imperative for any JavaScript developer to understand the difference between the call, apply, and bind methods.

Of the three, call is the easiest. It’s the same as invoking a function while specifying its context. Here’s an example:

var user = {
     name: "Rahul Mhatre",
     whatIsYourName: function() {
     console.log(this.name);
     }
};

user.whatIsYourName(); // Output: "Rahul Mhatre",
var user2 = {
     name: "Neha Sampat"
};

user.whatIsYourName.call(user2); // Output: "Neha Sampat"

apply is nearly the same as call. The only difference is that you pass arguments as an array and not separately. Arrays are easier to manipulate in JavaScript, opening a larger number of possibilities for working with functions. Here is an example using apply and call:

var user = {
     greet: "Hello!",
     greetUser: function(userName) {
     console.log(this.greet + " " + userName);
     }
};

var greet1 = {
     greet: "Hola"
};

user.greetUser.call(greet1,"Rahul") // Output: "Hola Rahul"

user.greetUser.apply(greet1,["Rahul"]) // Output: "Hola Rahul"

The bind method allows you to pass arguments to a function without invoking it. A new function is returned with arguments bounded preceding any further arguments. Here is an example:

           var user = {
                greet: "Hello!",
                greetUser: function(userName) {
                console.log(this.greet + " " + userName);
                }
           };

           var greetHola = user.greetUser.bind({greet: "Hola"});
           var greetBonjour = user.greetUser.bind({greet: "Bonjour"});

           greetHola("Rahul") // Output: "Hola Rahul"
           greetBonjour("Rahul") // Output: "Bonjour Rahul"

9. Memoization

Memoization is an optimization technique that speeds up function execution by storing results of expensive operations and returning the cached results when the same set of inputs occur again. JavaScript objects behave like associative arrays, making it easy to implement memoization in JavaScript. For example, we can convert a recursive factorial function into a memoized factorial function as shown below:

function memoizeFunction(func) {
  var cache = {};
  return function() {
            var key = arguments[0];
            if(cache[key]) {
            return cache[key];
            }
            else {
            var val = func.apply(this, arguments);
            cache[key] = val;
            return val;
            }
  };
}

var fibonacci = memoizeFunction(function(n) {
  return (n === 0 || n === 1) ? n : fibonacci(n - 1) + fibonacci(n - 2);
});

10. Method overloading

Method overloading allows multiple methods to have the same name but different arguments. The compiler or interpreter determines which function to call based on the number of arguments passed. Method overloading is not directly supported in JavaScript. But you can achieve something very much like it as shown below:

function overloadMethod(object, name, fn){

            if(!object._overload){
            object._overload = {};
            }

            if(!object._overload[name]){
            object._overload[name] = {};
            }

            if(!object._overload[name][fn.length]){
            object._overload[name][fn.length] = fn;
            }

              object[name] = function() {
                        if(this._overload[name][arguments.length])
                        return this._overload[name][arguments.length].apply(this, arguments);
              };
}

function Students(){
  overloadMethod(this, "find", function(){
            // Find a student by name
  });

  overloadMethod(this, "find", function(first, last){
            // Find a student by first and last name
  });

}

var students = new Students();
students.find(); // Finds all
students.find("Rahul"); // Finds students by name
students.find("Rahul", "Mhatre"); // Finds users by first and last name