Skip to content

Instantly share code, notes, and snippets.

@isRuslan
Created November 4, 2014 17:03
Show Gist options
  • Save isRuslan/e0273e8540b9dd041555 to your computer and use it in GitHub Desktop.
Save isRuslan/e0273e8540b9dd041555 to your computer and use it in GitHub Desktop.
AngularJS API Service
'use strict';
/**
* Welcome to the Api module!
* This is wrapper of $http angular service for Seedr Backend.
* In .config we defined interceptor, for cheking statuses all of Seedr requests.
*/
angular.module('Seedr.api', [])
/**
* @service Api
* Wrapper of $http service. Define all api method work with.
* how to use? This is common case:
Api.http('METHOD_NAME', '/path/to/api', { data: dataValue }, {param: paramValue}).then(function (response) {
return response;
});
*/
.factory('Api',['$http', '$q', function ($http, $q) {
var urlBase = '/api';
/**
* Public api methods
*/
var service = {
/**
* Main method to work with Backend.
* @param {String} method name
* @param {String} path to api
* @param {Obj} post data
* @param {Obj} url params
*/
http: function (method, url, data, params, cache) {
var params = params || ''
, deferred = $q.defer();
$http({
method: method,
url: urlBase + url + '/' + params,
data: data,
cache: cache
}).then(function (response) {
if (response) {
deferred.resolve(response);
} else {
deferred.reject(new Error('API Service Error'));
}
});
return deferred.promise;
},
post: function (url, data, params, cache) {
cache = cache || false;
return service.http( 'POST', url, data, params, cache );
},
get: function (url, params, cache) {
cache = cache || false;
return service.http( 'GET', url, null, params, cache );
},
put: function (url, data, params, cache) {
cache = cache || false;
return service.http( 'PUT', url, data, params, cache );
},
delete: function (url, data, params, cache) {
cache = cache || false;
return service.http( 'DELETE', url, data, params, cache );
}
};
return service;
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment