Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@koganei
Last active August 29, 2015 14:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koganei/47ca5f89e94e4bd60afd to your computer and use it in GitHub Desktop.
Save koganei/47ca5f89e94e4bd60afd to your computer and use it in GitHub Desktop.
An attempt to find the best way to structure a Restangularized API service
(function() {
'use strict';
/**
* the poemsApi Service. Restangular has all the functions you would expect from an
* API service, so we return the Restangular resource object.
*
* @service poemsApi
* @param Restangular bower install restangular
* @return service object
*/
var poemsApi = function poemsApi(Restangular) {
var service = Restangular.all('poems');
return service;
};
/**
* We use the RestangularProvider to add custom methods and custom paths.
* Other modules can use addElementTransformer themselves on your API
* to add custom fields to the resource
*/
poemsApi.setConfig = function setPoemsApiConfig(RestangularProvider) {
// every Restangular.all('poems') or Restangular.one('poems', someId) will make this function
// run on every element
RestangularProvider.addElementTransformer('poems', false, function transformPoemElements(poem) {
// custom functions for complex url paths
// addRestangularMethod(name, operation, [path, params, headers, elem])
poem.addRestangularMethod('flag', 'post', 'flag/myWeirdUrl', { source: 'myWebapp'}, { 'Accept': 'myweird/mimetype'});
// now calling poem.flag() will POST to flag/myWeirdUrl, with these parameters and with this particular header
// custom properties (for UX purposes), allows server-side to take it over
poem.isSelected = poem.isSelected || false;
// custom method
(poem.setValidationFromSchema = function setValidationFromSchema(schema) {
poem.all('schema').get().then(function getSchema(schema) {
poem.schema = schema;
poem.validate = function() {
// some validation code
};
});
})();
return poem;
});
};
// give it to Angular
angular.module('app')
.factory('poemsApi', poemsApi)
.config(poemsApi.setConfig);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment