utils.service.js
2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
(function() {
'use strict';
angular
.module('dialoga')
.factory('UtilService', UtilService);
/** @ngInject */
function UtilService($http, $q, $log) {
$log.debug('UtilService');
var service = {
get: get,
post: post,
// put: put,
// delete: delete,
// head: head,
handleSuccess: handleSuccess,
handleError: handleError
};
return service;
function get (url, config) {
return $http.get(url, config)
.then(handleSuccess)
.catch(handleError);
}
function post (url, config) {
return $http.post(url, config)
.then(handleSuccess)
.catch(handleError);
}
/**
* Transform the successful response, unwrapping the application data
* from the API response payload.
*
* @param {Object} response from the server.
* data – {string|Object} – The response body transformed with the transform functions.
* status – {number} – HTTP status code of the response.
* headers – {function([headerName])} – Header getter function.
* config – {Object} – The configuration object that was used to generate the request.
* statusText – {string} – HTTP status text of the response.
*
* @return {Object} the data unwrapped.
*/
function handleSuccess (response) {
$log.debug('[SUCCESS]', response);
return response.data;
}
/**
* Transform the error response, unwrapping the application data from
* the API response payload.
*
* @param {Object} error from the server.
* @return {Promise} promise rejection called.
*/
function handleError (error) {
$log.debug('[ERROR]', error);
$log.error('XHR Failed on Service.\n' + angular.toJson(error.data, true));
// The API response from the server should be returned in a
// nomralized format. However, if the request was not handled by the
// server (or what not handles properly - ex. server error), then we
// may have to normalize it on our end, as best we can.
if (!angular.isObject(error.data) || !error.data.message) {
return $q.reject('An unknown error occurred.');
}
// Otherwise, use expected error message.
return $q.reject(error.data);
}
}
})();