- 
      
- 
        Save gaboesquivel/a53980880ba63bb237e0 to your computer and use it in GitHub Desktop. 
    Angular.js REST API Service Wrapper
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | app.factory('API', function($http, $q){ | |
| var basePath = 'http://domain.com/api/path'; | |
| // => http://domain.com/api/path/foo/bar | |
| function makeRequest(verb, uri, data){ | |
| var defer = $q.defer(); | |
| verb = verb.toLowerCase(); | |
| //start with the uri | |
| var httpArgs = [basePath + uri]; | |
| if (verb.match(/post|put/)){ | |
| httpArgs.push( data ); | |
| } | |
| $http[verb].apply(null, httpArgs) | |
| .success(function(data, status){ | |
| defer.resolve(data); | |
| // update angular's scopes | |
| // $rootScope.$$phase || $rootScope.$apply(); | |
| }) | |
| .error(function(data, status){ | |
| defer.reject('HTTP Error: ' + status); | |
| }); | |
| return defer.promise; | |
| } | |
| return { | |
| get: function( uri ){ | |
| return makeRequest( 'get', uri ); | |
| } | |
| ,post: function( uri, data ){ | |
| return makeRequest( 'post', uri, data ); | |
| } | |
| ,put: function( uri, data ){ | |
| return makeRequest( 'put', uri, data ); | |
| } | |
| ,delete: function( uri ){ | |
| return makeRequest( 'delete', uri ); | |
| } | |
| }; | |
| }); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment