Angular : “url shortcuts”
A nice $http interceptor use-case
This article will show you how-to use what I call “custom protocol” or “url shortcuts” to improve your projets maintainability.
app.service(‘myService’, function($http) { // GET http://api.example.com/users
return $http.get(‘api://users’);});
How-to
Use-cases
Human readable configuration
Many api endpoints (big projects)
- “fileapi://” : file api (e.g: http://file.mywebsite.com)
- “app://” : app api (e.g: http://api.mywebsite.com)
Request transformation : “plain vs secure protocol”
- “api://” : basically replace “api://” by appConfig.api_url
- “apis://” : replace by api url + add auth HTTP headers “on the fly”
How-to
Using $http interceptors !
[interceptors] For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request […]
Module we use at Squareteam (responses part has been removed on purpose)
‘use strict’;// Handle API specific behavior for Requests and Responses
//
// ## Request
//
// All $http request starting with `api://`
// will be replace be API url
// If request url is `apis://` (notice the “s” for secure),
// then ApiCrypto will be called on request to
// add Authentification Headers
angular.module(‘squareteam.api’)
.factory(‘ApiHttpInterceptors’, function(ApiCrypto, appConfig) { var apiProtocolRegex = /^apis?:\/\//,
apiSecureProtocolRegex = /^apis:\/\//; return {
request : function(config) {
var isApiSecureCall = apiSecureProtocolRegex.test(config.url); if (apiProtocolRegex.test(config.url)) {
config.url = config.url.replace(
apiProtocolRegex,
appConfig.api.url
); if (isApiSecureCall) {
config = ApiCrypto.transformRequest(config);
} }
return config;
} // removed responses interceptor (next blogpost)});
This is pretty straight-forward, each request is intercepted by our ApiHttpInterceptors service.
This service changes the targeted endpoint with proper URL.
I developed a generic Angular module to handle this “fancy url” case.
It’s called “angular-fancy-url”.
The usage is the following :
app = angular.module('myApp', ['fancyURL']);
app.config(function($httpProvider, httpFancyURLProvider) { $httpProvider.interceptors.push('httpFancyURL'); httpFancyURLProvider.use({
'api' : 'http://api.example.com',
'fileapi' : 'http://file.example.com'
});});
You can find the bower package “angular-fancy-url” here !
Conclusion
Pros
- Flexibility — interceptors for the win !
- Readability — no extras string concatenation or helper calls
- “Testability” — you just have to mock appConfig in your test
Cons
- namespaces conflicts (in large projects ?)
- I let you submit feedback if you find more “Cons”
I’m currently working on a similar blogpost focusing on the response handling part.
It will show you how to handle many different response pattern depending on configured “url shortcuts”