Skip to content

Instantly share code, notes, and snippets.

@viezel
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save viezel/9839186 to your computer and use it in GitHub Desktop.

Select an option

Save viezel/9839186 to your computer and use it in GitHub Desktop.
Angular API - Restful
app.factory('API', ['$http', function($http){
// API url
var apiURL = "/api/v1/";
// defuauly HTTP Headers
var defaultHeaders = {
"X-API-KEY": angular.getAPIKey()
"X-SOMETHING": "123"
};
// example usage
// ex: db.fetch( "Book", 1234, function(response){ console.log(response.toString());} );
return {
create: function(className, data, callback) {
$http.post( apiURL+className, data, { headers: defaultHeaders } )
.success(function(response) {
$rootScope.$apply(function() { callback(null, response); });
})
.error(function(response) {
$rootScope.$apply(function() { callback("Cannot submit data!"); });
});
},
get: function(className, objectId, callback) {
$http.get( apiURL+className+'/'+objectId, { headers: defaultHeaders }
).success(function(response) {
$rootScope.$apply(function() { callback(null, response); });
}).error(function(response) {
$rootScope.$apply(function() { callback(response.error || "Cannot get object "+className+"/"+objectId+"!"); });
});
},
fetch: function(className, query, callback) {
var config = { headers: defaultHeaders };
if (query) config.params = { where: query };
$http.get( parseUrl+'/classes/'+className, config
).success(function(response) {
$rootScope.$apply(function() { callback(null, response); });
}).error(function(response) {
$rootScope.$apply(function() { callback(response.error || "Could not query "+className+"!"); });
});
},
update: function(className, data, callback) {
$http.put( apiURL+className, data, { headers: defaultHeaders } )
.success(function(response) {
$rootScope.$apply(function() { callback(null, response); });
})
.error(function(response) {
$rootScope.$apply(function() { callback("Cannot submit data!"); });
});
},
// delete is a reserved word in js
remove: function(className, objectId, callback) {
$http['delete']( apiURL+className+'/'+objectId, { headers: defaultHeaders }
).success(function(response) {
$rootScope.$apply(function() { callback(null, response); });
}).error(function(response) {
$rootScope.$apply(function() { callback(response.error || "Cannot delete object "+className+"/"+objectId+"!"); });
});
}
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment