30/11/2015 Development / java script

I did two implementations using promisses.

One using angular, and other using node.

Angular Implementation

---------------------------------------------------------------------------

    var myApp = angular.module('myApp',[]);
    function MyCtrl($scope, $http, $q, $timeout) {

        $scope.response = [];
        $scope.brands = ['shoptime', 'americanas', 'submarino'];

        $scope.update = function(data){

            var promises = [];

            $scope.brands.forEach(function(brand){

                var deferred = $q.defer();
                var url = 'https://api.'+ brand +'.com.br/';
                promises.push($http.get(url, {params: {brand : brand}}, function (error, msg, body) {
                  if (error) {
                    deferred.reject();
                  }
                  deferred.resolve();
                }));
            });

            $q.all(promises).then(function (resp) {

                $scope.response = [];
                var arr = [];

                resp.forEach(function(obj){

                  var brand = obj.config.params.brand;
                  var body = obj.data;

                  var oas = body.oas[brand];
                  var oassitepage = body.oassitepage[brand];
                  var ftpupload = body.ftpupload[brand];
                  arr.push({ 'oas' : oas, 'oassitepage': oassitepage, 'ftpupload': ftpupload, 'brand' : brand });
                });

                $scope.response = arr;
            });

            $timeout($scope.update, 5000);
        };

        $scope.update();
    };

 

Node Implementation - using socket.io

------------------------------------------------------------------------------------

function requestUrl(socket){

  var promises = [];

  brands.forEach(function (brand){
    var deferred = Q.defer();
    var options = {url: 'https://api.'+ brand +'.com.br/'};
    promises.push(request(options, function (error, msg, body) {
      if (error) {
        deferred.reject();
      }
      deferred.resolve();
    }));
  })

  Q.all(promises).then (function (resp) {
    var body = resp;
    var arr = [];

    resp.forEach(function(obj){

      brand = obj[0].request.uri.host.replace("api.", "");
      brand = brand.replace(".com.br", "");

      body = JSON.parse(obj[0].body);

      var oas = body.oas[brand];
      var oassitepage = body.oassitepage[brand];
      var ftpupload = body.ftpupload[brand];
      arr.push({ 'oas' : oas, 'oassitepage': oassitepage, 'ftpupload': ftpupload, 'brand' : brand });
    });

    socket.emit('news', { 'brands': arr });
  }).catch(function(err){
    console.log(err);
  });

For B2W Implementation