Skip to content

Instantly share code, notes, and snippets.

@LeonardoGentile
Forked from atuttle/api.js
Created July 8, 2014 21:55
Show Gist options
  • Save LeonardoGentile/424a7edfaf5fd4d1920c to your computer and use it in GitHub Desktop.
Save LeonardoGentile/424a7edfaf5fd4d1920c to your computer and use it in GitHub Desktop.
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