Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - How to deflate and encode/decode to base64 all jsons request?

Lets say i have several $resources and some $http around my angular application:

myApp.factory('Note', function($resource) {

  return $resource('http://', {id: '@id'}, 
    { 'index': { method: 'GET', isArray: true },
      'update': { method: 'PUT'},
    });
  });

with controller

myApp.controller('NotesController',function NotesController($scope, Note, AuthenticationService) {

$scope.notes = Note.index({}, function(data){
    console.log('success, got data: ', data);
    $scope.response = "yoy!"
  }, function(err){
    console.log('error, got data: ', err);
    $scope.response = "yay!"
  }); 
});

and some request are made by $http directly like authentication

var request = $http.post('http://', {email: email, password: password});

Where and How i can tell angular to deflate and encode/decode JSONs to base64 before the actual request is made / response is receive?

I quess i will wrap external libraries for deflate and encode/decode into factory. And then this factory will be injected somehere? Like $httpBackend ?

like image 564
Jakub Kuchar Avatar asked Dec 30 '12 12:12

Jakub Kuchar


People also ask

What is Base64 getEncoder ()?

getDecoder() Returns a Base64. Decoder that decodes using the Basic type base64 encoding scheme. static Base64.Encoder. getEncoder()

How do I decompress Base64?

To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.

Does converting to Base64 reduce size?

Although Base64 is a relatively efficient way of encoding binary data it will, on average still increase the file size for more than 25%. This not only increases your bandwidth bill, but also increases the download time.

What is BTOA in angular?

btoa() The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data).


2 Answers

You should have a look at the request / response transformers for the $http service: http://docs.angularjs.org/api/ng.$http

Request / response transformers are simply functions that can be invoked before content is sent / handed back to the caller. You can specify transforming functions globally (for all requests / responses) as well as per-request basis:

To override these transformation locally, specify transform functions as transformRequest and/or transformResponse properties of the config object. To globally override the default transforms, override the $httpProvider.defaults.transformRequest and $httpProvider.defaults.transformResponse properties of the $httpProvider.

To define global request / response transformers one would write the code along those lines (it is more like pseudo-code, won't work in all browsers, see notes about Base64 below):

angular.module('sample', [], function($httpProvider) {

    $httpProvider.defaults.transformRequest = function(data, headersGetter) {
        return btoa(JSON.stringify(data));
    };

    $httpProvider.defaults.transformResponse = function(data, headersGetter) {
        return JSON.parse(atob(data));
    };

})

Of course your transforming code could be more sophisticated and depend on request / response headers but the general idea is here. The jsFiddle with the code (check the console to see that a request gets transformed, you need to use Mozilla or a WebKit browser): http://jsfiddle.net/Ydt5j/

For the actual conversion from / to Base64 check this question: How can you encode a string to Base64 in JavaScript?

like image 163
pkozlowski.opensource Avatar answered Sep 23 '22 07:09

pkozlowski.opensource


angular.module('services.base64',[]);
angular.module('services.base64').provider('base64', function () {

  this.encode = function(str) {
    return base64_encode(str);
  }

  this.decode = function(str) {
    return base64_decode(str);
  }

  this.$get = function() {
    return {};
  }

});

var myApp = angular.module('myApp',['services.base64'])

myApp.config(['base64Provider', function (base64Provider) {
    $httpProvider.defaults.transformRequest = function(request){return base64Provider.encode(request)};

    $httpProvider.defaults.transformResponse = function(response){return base64Provider.decode(response)};
}]);
like image 22
Jakub Kuchar Avatar answered Sep 25 '22 07:09

Jakub Kuchar