Skip to content

Instantly share code, notes, and snippets.

@dddent
Last active January 18, 2016 10:56
Show Gist options
  • Save dddent/c29f6964ed97fb912958 to your computer and use it in GitHub Desktop.
Save dddent/c29f6964ed97fb912958 to your computer and use it in GitHub Desktop.
API call varianten
mcDataService().then(function(apiObject) {
apiObject.template.get(2).then(function(data) {
// do stuff w/ data
},
function(err, res) {
console.log('error getting template.');
});
},
function (err) {
console.log('error recieving apiObject');
});
mcDataService('template').get(2).then(function(data) {
// do stuff w/ data
},
function(err, res) {
console.log('error getting templates.')
});
(function () {
var module = angular.module('MedCloudData');
var serviceName = 'mcDataService';
module.provider(serviceName, function mcDataServiceProvider() {
var apiJsonLocation = '';
this.setApiJsonLocation = function (location) {
apiJsonLocation = location;
}
this.$get = [
'$http',
'$q',
function ($http, $q) {
return function () {
var def = $q.defer();
var apiObject = {};
$.getJSON(apiJsonLocation, function (apiData) {
for (var key in apiData) {
apiObject[key] = {}
if (!apiData[key].GET) apiObject[key].get = null;
else {
apiObject[key].get = function (params) {
var getDef = $q.defer();
var formattedUrl = (apiData[key].url[apiData[key].url.length - 1] == '/') ? apiData[key].url : apiData[key].url + '/';
for (var i in apiData[key].GET.params) {
if (!params[apiData[key].GET.params[i]]) {
return getDef.reject(new Error('Parameter "' + apiData[key].GET.params[i] + '" missing.'));
}
formattedUrl += params[apiData[key].GET.params[i]] + '/';
}
formattedUrl = (formattedUrl[formattedUrl.length - 1] == '/')
? formattedUrl.substr(0, formattedUrl.length - 1) : formattedUrl;
$http.get(formattedUrl).then(function (res) {
getDef.resolve(res.data);
},
function (res) {
getDef.reject(new Error('Error on "' + key + '" GET request.'), res);
});
return getDef.promise;
}
}
if (!apiData[key].POST) apiObject[key].post = null;
if (!apiData[key].PUT) apiObject[key].put = null;
if (!apiData[key].DELETE) apiObject[key].delete = null;
}
def.resolve(apiObject);
});
return def.promise;
}
}
];
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment