Leave a comment

Solve CORS Cross-origin issue in Development Environment

Developing a front-end application, let’s say an Angular app, you could run into CORS Cross-origin issues performing requests to back-end services.

XMLHttpRequest cannot load http://my-service/api/my-resource. Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8000’ is therefore not allowed access.

In production is something that should be configured in the server adding the following header to its response:

Access-Control-Allow-Origin: *

And the same can be done in your local dev machine if you are serving the fron-end and also the back-end. But what happens if your service is in another machine or port?

We can solve this problem with a local reverse proxy, or using apps like Burp Suite. But a really quick workaround is to use the Google Chrome Allow-Control-Allow-Origin plugin.

Don’t forget to configure properly the filters to intercept only the URLs to the services that you use:

http://my-service/api/my-resource/*

CORS_chrome_plugin

Another hacky and quick way to solve this is opening chrome with the web security disabled:

open /Applications/Google\ Chrome.app/ --args --disable-web-security

but It could be really dangerous to use that all the time.

To know more about CORS read http://www.html5rocks.com/en/tutorials/cors/.

Leave a comment

Design Patterns – Facade

The Facade Pattern is used to provide a simplified interface to a complicated subsystem.

The idea is to define a higher-level interface that abstracts clients from using directly a set of lower level interfaces in the subsystem. For some clients accessing directly the subsystem could make perfect sense because they benefit from the different options and flexibility of a rich API. However, most of the clients only need basic functionality, accessing a large set of interfaces only bring them complexity.

This pattern is commonly used during refactoring to simplify the use of a legacy code subsystem.

One important difference between this structural pattern and the Decorator pattern is that the goal in Facade is not to add new functionality.

Real examples

* JQuery
JQuery is a good example of Facade Pattern, providing a simple and clean interface to interacting with the complex DOM of the browser.

* Java URL class

URL url = new URL("http", "www.google.ie", 80, "/";);
url.openStream()

https://docs.oracle.com/javase/8/docs/api/java/net/URL.html

Code example

class FlightsService {
  findFlightsFor(city, date) {
    console.log(`Searching for flight to ${city} on ${date}`);
  }

  book(flightNumber, airline, date) {
    console.log(`Booking flight ${flightNumber} - ${airline} on ${date}`);
  }
}

class HotelsService {
  findHotelsFor(city, checkinDate, checkoutDate) {
    console.log(`Searching for hotels on ${city} from ${checkinDate} to ${checkoutDate}`);
  }

  book(roomNumber, hotel, checkinDate, checkoutDate) {
    console.log(`Booking room ${roomNumber} - ${hotel} from ${checkinDate} to ${checkoutDate}`);
  }
}

class TravelFacade {
  constructor() {
    this.flightsService = new FlightsService();
    this.hotelsService = new HotelsService();
  }

  findFlightsAndHotels(city, travelDate, returnDate) {
    this.flightsService.findFlightsFor(city, travelDate);
    this.flightsService.findFlightsFor(city, returnDate);
    this.hotelsService.findHotelsFor(city, travelDate, returnDate);
  }
}

Documentation

https://en.wikipedia.org/wiki/Facade_pattern
http://www.joezimjs.com/javascript/javascript-design-patterns-facade/
https://dzone.com/articles/design-patterns-uncovered-1
http://www.dofactory.com/javascript/facade-design-pattern

Leave a comment

Useful Faker.js API and demo page

In my angular projects,​ I use the faker.js library to generate fake data for the test fixture factories used by my unit tests and the dev application running with a stubbed back-end. It is a convenient and consistent way to generate data that looks real and makes the code of our fixtures really simple. The Faker.js API documentation is really basic and sometimes it not obvious what kind of values it can generate.
To help with that you can use the next demo page http://marak.com/faker.js/ that shows examples of generated data for each of the faker.js API methods.

faker_demo

I encourage to use it and get familiar with the faker API to improve the quality of our test data.

Leave a comment

Bower Guideline – Always Ignore the files that you don’t want to publish

The bower.json defines several options, one of those is the ignore option:

ignore [array]: An array of paths not needed in production that you want Bower to ignore when installing your package.

It is really important to use it when you are defining a bower.json of a package that is meant to be used from other apps or modules.

Why?
When a consumer installs your package via Bower, it will download your project’s entire git repository into their project. But in most of the cases, we don’t want to distribute everything. The consumer app doesn’t need things like​ tests, configuration files, tasks, etc. Only the original and minified versions of the component and the documentation. That will save time downloading the module and disk space.

Guideline
The rule of thumb is to use the ignore attribute to define the list of files and directories that we don’t want to publish.

For example:

"ignore": [
"gulp",
".bowerrc",
".gitignore",
"gulpfile.js",
"package.json",
"README.md"
],

2 Comments

Angular-ui-grid enable filtering from grid menu

In Angular ui-grid it is possible to configure the grid with filtering using the enableFiltering option.

vm.gridOptions = {enableFiltering: true};

I wanted to allow the user to hide/show the filter clicking a button.
There is an example of that in http://ui-grid.info/docs/#/tutorial/103_filtering, but I wanted to add that action to the grid menu itself.

angular-ui-grid-enable-filtering-grid-menu-01

angular-ui-grid-enable-filtering-grid-menu-02

Here is the code of my solution:

            vm.gridOptions.gridMenuCustomItems = [
                {
                    title: 'Hide filter',
                    icon: 'glyphicons filter failure',
                    leaveOpen: true,
                    order: 0,
                    action: function ($event) {
                        this.grid.options.enableFiltering = !this.grid.options.enableFiltering;
                        this.grid.api.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
                    },
                    shown: function () {
                        return this.grid.options.enableFiltering;
                    }
                },
                {
                    title: 'Show filter',
                    icon: 'glyphicons filter success',
                    leaveOpen: true,
                    order: 0,
                    action: function ($event) {
                        this.grid.options.enableFiltering = !this.grid.options.enableFiltering;
                        this.grid.api.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
                    },
                    shown: function () {
                        return !this.grid.options.enableFiltering;
                    }
                }
            ];

You can see that doesn’t need to expose the grid to scope in a onRegisterApi block.

Documentation:
http://ui-grid.info/docs/#/tutorial/103_filtering
http://ui-grid.info/docs/#/tutorial/121_grid_menu

Leave a comment

Angular – Caching $http calls using $cacheFactory service

In this post I am going to explain how we can cache requests to REST backends in our angular applications.

Introduction to $cacheFactory
Angular $cacheFactory is a service that allows us to create and access Cache objects. Think on a Cache as a simple key value store with put, get, destroy methods.

var myCache = $cacheFactory('cacheId');
myCache.put('key', 'value');
console.log(myCache.get('key'));

The angular $http services could use that Cache objects to cache response data.

angular.module('app', [])
    .factory('MyService', function ($http, $cacheFactory) {
		var myCache = $cacheFactory('cacheId');
        return {
            getPerson: function (id) {
                $http
                    .get('//server.com/api/people/' + id + '/', {cache: myCache})
                    .then(function (result) {
                        console.log(result.data.name);
                    });
            }
        }
    });

It uses the request URL as a key to store values. In the previous example if we call getPerson for the same person twice it will perform a http request only the first time and will return directly from the cache the second time.

Caching in Swagger APIs
In my current apps I don’t use directly the $http service to interact with the backend APIs, instead I use swagger generated API services that abstract me from writing that code. But the generated services allows also to use cache functionality. The way that we should use it is passing a cache object as a parameter of the services methods.
For example, we have the API service CurrentUserApi and its method getCurrentUser.

var currentUserApi = new CurrentUserApi(RestDomains.myService);
currentUserApi.getCurrentUser();

And we want to use cache here to avoid hitting the backend multiple times. The only thing that we need to do is to pass a Cache object as a param of the getCurrentUser method and the API service will use it to cache requests. Again, notice that we don’t need to deal with the complexity of managing the cache ourselves.

var currentUserApi = new CurrentUserApi(RestDomains.myService);
var currentUserCache = $cacheFactory('currentUser');
currentUserApi.getCurrentUser({$cache: currentUserCache});

Using a CacheService
We can simplify the use of the cache in our services using the same cache object. For that we can create a singleton CacheService with a local cache created with $cacheFactory. It can be injected in our services and passed directly as the cache param.

angular
    .module('App')
    .factory('CacheService', ['$cacheFactory', function ($cacheFactory) {
        return $cacheFactory('CacheService');
    }]);
 
 
angular
    .module('App')
    .factory('UsersService', ['RestDomains', 'CacheService', 'CurrentUserApi', function (RestDomains, CacheService, CurrentUserApi) {
    var currentUserApi = new CurrentUserApi(RestDomains.myService);

    return {
        getCurrentUser: function () {
            return currentUserApi.getCurrentUser({$cache: CacheService});
        }
    };
}]);

Considerations
The use of caching in the angular services could reduce the number of requests that the single page application performs, improving performance and making the UI more responsive. But it is really important to choose properly the endpoints and resource to cache. Usually we want to cache resources that we now that are not going to change during the user “session”, resources like current user information, reference data, etc.

It is possible to use different implementations of the $cacheFactory services like angular-cache that provides Cache objects with timeouts or the possibility of caching using HTML5 local storage. The good thing of the angular’s built-in version is its simplicity.

Notice also that the use of Cache objects directly by the $http or the swagger APIs services it is a cleaner option that dealing directly in our service with the cache of values.

Documentation:
https://docs.angularjs.org/api/ng/service/$cacheFactory
https://egghead.io/lessons/angularjs-cachefactory
http://jmdobry.github.io/angular-cache/
https://github.com/wcandillon/swagger-js-codegen

Leave a comment

Mock an Angular Service

When we unit test an angular controller we test it in isolation replacing​ the services that the controller uses with test doubles (aka mocks). In Jasmine, the kind of test double used is called Spy​. (Read more: http://jasmine.github.io/2.0/introduction.html)

The next code example shows the most basic beforeEach initialization block for a controller test suit. In it we use the $controller service to instantiate the controller under test MyCtrl injecting a new clean $scope before each test execution.

beforeEach(inject(function ($rootScope, $controller) {
    scope = $rootScope.$new();
 
    $controller('MyCtrl', {
        $scope: scope // inject the stubbed scope
    });
}));

During the instantiation of the controller, we can configure the mock services or stubbed data to inject. Notice that for all the dependencies that we don’t configure explicitly​ the unit test will use the real ones.
There are different ways to mock dependencies, I am going to show two alternatives here:

Replacing a service by a spy object

var stateSpy;
 
beforeEach(inject(function ($rootScope, $controller, MyService) {
    scope = $rootScope.$new();
    controller = $controller;
 
    stateSpy = jasmine.createSpyObj('$state', ['go']); // create a test double for a $state service with function called go
 
    $controller('MyCtrl', {
        $scope: scope,
        $state: stateSpy // inject the test double in the controller
    });
 
}));

Replacing the functions of a service by spies
Let’s say that MyCtrl makes use of a function getData() on a service called MyService. We can remplace that function with an spy and fake their response.

beforeEach(inject(function ($rootScope, $q, $controller, MyService) {
    scope = $rootScope.$new();
    q = $q;
    controller = $controller;
 
    spyOn(MyService, 'getData').and.callFake(function () {
        var deferred = $q.defer();
        deferred.resolve(TEST_DATA);
        return deferred.promise;
    });
 
    $controller('MyCtrl', {
        $scope: scope
    });
 
}));

With this approach, we are replacing the functions of a service,​ not the service itself. If the function to spy doesn’t exist in the service the test will fail.

Follow

Get every new post delivered to your Inbox.