Created
February 16, 2016 11:06
-
-
Save renesansz/0f2b9def054d936ace0e to your computer and use it in GitHub Desktop.
$http interceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* App Factory: httpInterceptor | |
* ------------------------- | |
* The $http interceptor. | |
* This is where you can modify the $http message before/after the request is sent to the server. | |
* | |
* Here's a very useful article regarding $http interceptors: | |
* https://thinkster.io/interceptors | |
* | |
* USEFUL TIP: | |
* You can directly refer to the Engage API by just passing the api route in the URL parameter. | |
* eg: $http.post('/o/token', apiParam) | |
* This will automatically determine that you will be calling the Engage API, | |
* unless you provide another specific url. eg: $http.post('https://another-api/just/another/method', apiParam). | |
* See httpInterceptor.js for reference. | |
*/ | |
(function() { | |
'use strict'; | |
angular.module('Engage.Factories').factory('httpInterceptor', httpInterceptor); | |
function httpInterceptor($q, ENGAGE_API) { | |
return { | |
request: OnRequest | |
}; | |
//////////////////////////// | |
/// FUNCTION DEFINITIONS /// | |
//////////////////////////// | |
/** | |
* On request interceptor. | |
* | |
* @param {Object} req - The $http request | |
* | |
* @return {Promise} | |
*/ | |
function OnRequest(req) { | |
var d = $q.defer(); | |
// If the url starts with forward slash (/), | |
// we will assume that we are referring to the Engage API. | |
// So we'll change the target URL before sending a $http request to avoid request error. | |
if (req.url.indexOf('/') === 0) | |
req.url = ENGAGE_API.BASE_URL + req.url; | |
d.resolve(req); | |
return d.promise; | |
} | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment