Mastering Web Application

(Rick Simeone) #1
Chapter 3
return Resource.remove(this);
};

//other CRUD methods go here

//convenience methods
Resource.prototype.$id = function () {
return getId(this);
};

return Resource;
};
});

The example code starts by declaring a new module (mongolabResource) and a
factory (mongolabResource) accepting a configuration object (MONGOLAB_CONFIG)
those are the parts that should look familiar by now. Based on a provided
configuration object we can prepare a URL to be used by a resource. Here we are in
total control of how a URL is created and manipulated.


Then, the Resource constructor is declared, so we can create new resource objects
from existing data. What follows is a definition of several methods: query, save and
remove. Those methods are defined on the constructor (class) level, but instance-level
methods are also declared (where appropriate) to follow the same convention as the
original $resource implementation. Providing an instance-level method is as easy as
delegating to the class-level one:


Resource.prototype.$save = function (data) {
return Resource.save(this);
};

Usage of promise chaining is the crucial part of the custom resource implementation.
The then method is always called on a promise returned from a $http call, and a
resulting promise is returned to the client. A success callback on a promise returned
from a $http call is used to register post-processing logic. For example, in the query
method implementation we post-process raw JSON returned from a back-end, and
create resource instances. Here, once again we've got full control over data extraction
process from a response.


Let's examine how a new resource factory could be used:


angular.module('customResourceDemo', ['mongolabResource'])
.constant('MONGOLAB_CONFIG', {
DB_NAME: 'ascrum',
API_KEY: '4fb51e55e4b02e56a67b0b66'
})
Free download pdf