[AngularJS] transform in $http services
transform is used to format json or whatever return from the server.
Usage:
Profile.factories = angular.module("profileFactories", []); Profile.factories.factory('Skills', ['$http', '$q', 'ProfileTransformer', function($http, $q, ProfileTransformer){ return{ getSkills: function(){ var deferred = $q.defer(); $http({ url: './public/js/profile/skills.json', cache: true, method: "GET", transformResponse: ProfileTransformer }) .success(function(data){ return deferred.resolve(data); }); return deferred.promise; } } }]);
var apiTransform = angular.module("publicTransformer", []); apiTransform.factory('ProfileTransformer', function () { return function(data){ data = JSON.parse(data); if(_.size(data)>0){ data = _.map(data, function(d){
//Here we format JSON according to what we want! return {name: d.name, level: d.level, bold_normal: d.b} }) } return data; } });
Unit Testing:
/** * Created by Answer1215 on 9/5/2014. */ describe("transform tresponse", function(){ var transformer, response; beforeEach(function () { module('publicTransformer'); inject(function ($injector) { transformer = $injector.get('ProfileTransformer'); }); }); it("should return an empty array when it receives an empty array", function(){ expect(transformer('[]')).toEqual([]); }); it("should return 2 items with name level and b", function(){ expect(transformer(response)).toEqual([ {"name": "Hadoop", "level": "Learning", "b": "normal"}, {"name": "D3.js", "level": "Learning", "b": "bold"} ]) }) beforeEach(function(){ response = JSON.stringify( [ {"name": "Hadoop", "level": "Learning", "b": "normal"}, {"name": "D3.js", "level": "Learning", "b": "bold"} ] ) }) })