-
Notifications
You must be signed in to change notification settings - Fork 105
Design: Structuring Client Services
Jonathan Niles edited this page May 6, 2016
·
2 revisions
In order to facilitate easily reading and reviewing the code (as well as nice JSDoc layouts), we have adopted the following guidelines for creating services within the application.
- Always use services over factories, unless a specific use case is desired.
- Always use the suffix 'Service' at the end of the service name.
- Always alias
var service = this
at the top of the service function. - Always bind service methods at the top of the service function declaration. The method definitions should be declared later.
- Always write JSDoc documentation comments at the function definition.
- Always return
service
at the bottom of the service function declaration.
Here is an example:
angular.module('bhima.services') // note: we are creating a 'service' instead of a 'factory'
.service('SomeService', SomeService); // note: this name contains the suffix Service
SomeService.$inject = [ '$http', 'util' /*, other injects ... */];
function SomeService($http, util) {
var service = this; // note: we are aliasing the `this` reference.
/** @method read */
service.read = read;
/** @method someOtherMethod */
service.someOtherMethod = someOtherMethod;
// ....
/**
* The read methods returns detailed records from the database
* @param {Number} id A numerical id found in the database
* @example
* SomeService.read(id)
* .then(function (record) {
* vm.record = record;
* });
* @returns {Object} promise A promise object with the response.body inside.
*/
function read(id) {
return $http.get('/some/endpoint' + id)
.then(util.unwrapHttpResponse);
}
/**
* blah, blah, blah
* .... more JSDoc documentation
*/
function someOtherMethod() {
// ... code ...
}
return service; // Note: returning service at the bottom of the service.
}