How can I extend the constructor of an AngularJS resource ($resource)?

折月煮酒 提交于 2019-11-29 22:33:16

$resource is a simple implementation, and lacks in things like this.

User.prototype.constructor won't do anything; angular doesn't try to act like it's object oriented, unlike other libraries. It's just javascript.

..But luckily, you have promises and javascript :-). Here's a way you could do it:

function wrapPreferences(user) {
  user.preferences = _.map(user.preferences, function(p) {
    return new Preference(p);
  });
  return user;
}

var get = User.get;
User.get = function() {
  return get.apply(User, arguments).$then(wrapPreferences);
};
var $get = User.prototype.$get;
User.prototype.$get = function() {
  return $get.apply(this, arguments).$then(wrapPreferences);
};

You could abstract this into a method which decorates any of a resource's methods: It takes an object, an array of method names, and a decorator function.

function decorateResource(Resource, methodNames, decorator) {
  _.forEach(methodNames, function(methodName) {
    var method = Resource[methodName];
    Resource[methodName] = function() {
      return method.apply(Resource, arguments).$then(decorator);
    };
    var $method = Resource.prototype[methodName];
    Resource.prototype[methodName] = function() {
      return $method.apply(this, arguments).$then(decorator);
    };
  });
}
decorateResource(User, ['get', 'query'], wrapPreferences);

You can do this by overriding the built-in resource actions to transform the request and response (See transformRequest and transformResponse in the docs.):

var m = angular.module('my-app.resources');
m.factory('User', [
          '$resource',
  function($resource) {

    function transformUserFromServer(user) {
      // Pass Preference directly to map since, in your example, it takes a JSON preference as an argument
      user.preferences = _.map(user.preferences, Preference);
      return user;
    }

    function transformUserForServer(user) {
      // Make a copy so that you don't make your existing object invalid
      // E.g., changes here may invalidate your model for its form, 
      //  resulting in flashes of error messages while the request is 
      //  running and before you transfer to a new page
      var copy = angular.copy(user);
      copy.preferences = _.map(user.preferences, function(pref) {
        // This may be unnecessary in your case, if your Preference model is acceptable in JSON format for your server
        return {
          id: pref.id,
          title: pref.title,
          value: pref.value
        };
      });

      return copy;
    }

    function transformUsersFromServer(users) {
      return _.map(users, transformUserFromServer);
    }

    return $resource('/user/:userId', {
        userId: '@id'
      }, {
        get: {
          method: 'GET',
          transformRequest: [
            angular.fromJson,
            transformUserFromServer
          ]
        },
        query: {
          method: 'GET',
          isArray: true,
          transformRequest: [
            angular.fromJson,
            transformUsersFromServer
          ]
        },
        save: {
          method: 'POST',
          // This may be unnecessary in your case, if your Preference model is acceptable in JSON format for your server
          transformRequest: [
            transformUserForServer,
            angular.toJson
          ],
          // But you'll probably still want to transform the response
          transformResponse: [
            angular.fromJson,
            transformUserFromServer
          ]
        },
        // update is not a built-in $resource method, but we use it so that our URLs are more RESTful
        update: {
          method: 'PUT',
          // Same comments above apply in the update case.
          transformRequest: [
            transformUserForServer,
            angular.toJson
          ],
          transformResponse: [
            angular.fromJson,
            transformUserFromServer
          ]
        }
      }
    );
  };
]);

I was looking for a solution to the same problem as yours. I came up with the following approach.
This example is based on Offers instead of Users, as domain entity. Also, please note here's a trimmed down version of the whole thing, which in my case spans over some files:

Domain entity custom class:

function Offer(resource) {
    // Class constructor function
    // ...
}

angular.extend(Offer.prototype, {
    // ...

    _init: function (resource) {
        this._initAsEmpty();

        if (typeof resource == 'undefined') {
            // no resource passed, leave empty
        }
        else {
            // resource passed, copy offer from that
            this.copyFromResource(resource);
        }
    },

    copyFromResource: function (resource) {
        angular.extend(this, resource);
        // possibly some more logic to copy deep references
    },

    // ...
});

Classic angular custom resource:

var offerResource = $resource(/* .. */);

Custom repository, passed to controller by a service factory:

function OfferRepository() {  
    // ...
}

angular.extend(OfferRepository.prototype, {
    // ...

    getById: function (offerId, success, error) {

        var asyncResource = offerResource.get({
            offerId: offerId

        }, function (resource) {
            asyncOffer.copyFromResource(resource);

            (success || angular.noop)(asyncOffer);

        }, function (response) {
            (error || angular.noop)(response);

        });

        var asyncOffer = new offerModels.Offer(asyncResource);

        return asyncOffer;
    },

    // ...
});

Most noticeable parts are:

  • the custom entity class, that is able to construct/fill itself starting from a resource instance (possibly with deep copy capabilities, e.g. Positions in an Offer)
  • the custom repository class, which wraps the resource. That does not returns the classic async resource answer, but instead returns an custom entity instance, and later on it fills that with the resource just loaded.

Attempting to modify the constructor property of the prototype object won't do what you expect anyhow, please take a look at the very nice post here.

To really understand what is going on, one should look at the source code of the ngResource module - there are a lot of things at work there, but what's important is that the $resource factory returns a plain JavaScript function (really, what else). Invoking this function with the documented parameters returns a Resource constructor object, which is defined privately in resourceFactory.

As you may recall, AngularJS services are singletons, meaning that calling $resource will return the same function every time (in this case, resourceFactory). The important takeaway is that every time this function is evaluated, a new Resource constructor object is returned, meaning that you can prototype your own functions on it safely, without worrying that this will pollute all Resource instances globally.

Here is a service that you can use much as the original $resource factory, while defining your own custom methods that will be available on all of its instances:

angular.module('app').factory('ExtendedResourceFactory', ['$resource',
  function($resource) {                                                        
    function ExtendedResourceFactory() {
      var Resource = $resource.apply(this, arguments);

      Resource.prototype.myCustomFunction = function() {
        ...
      };

      return Resource;
    }

    return ExtendedResourceFactory;
  }
]);

Inside myCustomFunction you have access to the data returned from the server so you can use this.preferences and return whichever custom class you want to build.

transformResponse does the job. Consider example (I wanted to use Autolinker to format response content).

return $resource('posts/:postId', {
    postId: '@_id'
}, {
    get : {
        transformResponse : function(data) {
            var response = angular.fromJson( data );
            response.content = Autolinker.link(response.content);
            return response;
        }
    },
    update: {
        method: 'PUT'
} });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!