10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

angularでmessagepack

Posted at

messagepackのライブラリは https://github.com/uupaa/msgpack.js を使用。

ngMsgpack.js
angular.module('ngMsgpack', []).config(function($provide, $httpProvider) {
  
  // リクエストするときに余計なことをさせないようにする&オブジェクトはmessagepack形式に変換
  $httpProvider.transformRequest = [function(data) {
    switch (Object.prototype.toString(data)) {
      case '[object Uint8Array]':
      case '[object Int8Array]':
      case '[object Uint16Array]':
      case '[object Int16Array]':
      case '[object Uint32Array]':
      case '[object Int32Array]':
      case '[object Float32Array]':
      case '[object Float64Array]':
      case '[object CanvasPixelArray]':
      case '[object Uint8ClampedArray]':
      case '[object File]':
      case '[object Blob]':
        return data;
    }
    if (data !== null && typeof data === 'object') {
      return msgpack.pack(data);
    } else {
      return data;
    }
  }];

  // $httpBackendをラップ
  $provide.decorator('$httpBackend', function($delegate) {
    return function $httpBackend(method, url, post, callback, headers, timeout, withCredentials, responseType) {
      var xhr = new XMLHttpRequest;
      xhr.open(method, url);
      xhr.responseType = 'arraybuffer';
      angular.forEach(headers, function(v, k) {
        if (angular.isDefined(v)) {
          xhr.setRequestHeader(k, v);
        }
      });
      xhr.onloadend = function() {
        var responseHeaders = xhr.getAllResponseHeaders();

        if (xhr.status === 200) {
          callback(xhr.status, msgpack.unpack(new Uint8Array(xhr.response)), responseHeaders);
        } else {
          callback(xhr.status, null, responseHeaders);
        }
      };
      xhr.send(post || null);
    }
  });

});

つかうときはいつも通りこんなかんじで。

app.js
angular.module('foo', ['ngMsgpack']).controller(function($scope, $http) {
  $http({
    method: 'POST',
    url: '/foo',
    data: {
      a: 1,
      b: 'bar'
    }
  }).success(...);
});
10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?