Last active
August 29, 2015 14:04
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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