0

I'd like to get objects from a server, something like:

var User = $resource('/user/:userId', {userId:'@id'});

I'd like User instances to all have certain methods to calculate derived data, without the server having to return it. For example, say for:

var aUser = User.get({userId: 43});

The server returns something like:

{id: 43, name: "Bob", alertTimestamp: 1447365544}

I'd like to be able to do something like:

if (aUser.alertTimePassed()) {
    // do stuff
}

Is there a clean way to do this short of something like this, which seems hacky?

var alertTimePassed = function () {
    var now = (new Date()).getTime() / 1000;
    return now >= this.alertTimestamp;
};
var User = $resource('/user/:userId', {userId: '@id'}, {
    get: {
        method: "GET", url: '/user/:userId',
        transformResponse: [angular.fromJson, function (obj) {
            obj.alertTimePassed = alertTimePassed;
        }]
    }
});
Claudiu
  • 224,032
  • 165
  • 485
  • 680
  • 2
    There are similar questions and answers out there already. http://stackoverflow.com/questions/17134401/angular-extending-resource-subobject-with-custom-methods| http://stackoverflow.com/questions/18138147/add-a-custom-function-on-angular-resource – mark Nov 12 '15 at 22:32

1 Answers1

0

If you create your $resource using a factory you can modify the $resource object before returning it from the factory.

app.factory('User', function ($resource) {
    var User = $resource('/user/:userId', {userId: '@id'});

    // add any methods here using prototype
    User.prototype.alertTimePassed = function() {
        // do stuff
    };

    return User;
});
mark
  • 1,573
  • 13
  • 27