vokal-ng-api
v8.0.0
Published
Vokal's common Angular 1.x API service
Downloads
4
Readme
vokal-ng-api
Vokal's common Angular 1.x API service. Wraps Angular's $http
service.
Maintained by @Tathanen
Configuration & Usage
The API
service returns a constructor function that can be used to instantiate a helper for an HTTP API.
var Facebook = new API();
The service can be configured by setting individual properties, or by passing an optional configuration object at instantiation.
var Facebook = new API();
Facebook.rootPath = "https://graph.facebook.com/";
Facebook.transformHumps = false;
Facebook.setKey( token );
var Facebook = new API( {
rootPath: "https://graph.facebook.com/",
transformHumps: false,
globalHeaders: { Authorization: token }
} );
You can instantiate the service on the fly for single usage, but the recommended pattern is to create a dedicated service that returns a pre-configured instance.
angular.module( "vokal.Facebook", [ "vokal.API" ] )
.factory( "Facebook", [ "API",
function ( API )
{
"use strict";
var Facebook = new API( {
rootPath: "https://graph.facebook.com/",
transformHumps: false,
globalHeaders: { Authorization: token }
} );
return Facebook;
}
] );
The following properties can be set directly or via the constructor config object:
- name
- globalHeaders
- rootPath
- keyName
- transformHumps
- cancelOnRouteChange
- unauthorizedInterrupt
- loginPath
- loginRoutes
Several methods are available during direct configuration:
Properties
name
String | Default: ""
A string to uniquely identify the API service. This is useful when listening to the events generated by the service, as you can check it to make sure you're listening to the correct API. It is exposed on the options
object sent into the Angular $http
request, and available as options.ngName
.
globalHeaders
Object | Default: {}
Supplied key/value pairs will be sent as request headers on API calls. While this property can be accessed directly, calling extendHeaders( headers ) is recommended to minimize the danger of losing already-set headers (like the authorization key).
rootPath
String | Default: ""
All API requests will be prepended with the supplied string.
keyName
String | Default: "Authorization"
The name of the header field in which your API's key or token should be stored.
transformHumps
Boolean | Default: true
The request body will have its parameter names changed from camel case to underscore format before being sent, and the response body will have its parameter names changed from underscore to camel case format before arriving.
cancelOnRouteChange
Boolean | Default: false
Enable by setting to true
. When the application route changes, any in-progress API calls will be canceled.
unauthorizedInterrupt
Boolean or Function | Default: false
Enable basic functionality by setting to true
. When a request on a non-login page returns a 401
status code, the normal error-handler events will not be fired, and the request promise will not be rejected. This allows for clean handling of the APIRequestUnauthorized
event, which may implement a redirect to a login page or otherwise attempt to resolve an authorization error.
If a function is supplied for this value, it should be used as an attempt to resolve an authorization issue. For example, an expired token could be exchanged for a fresh one, and re-added to the service via setKey()
. This function should return a promise that is resolved or rejected depending upon whether or not it was successful in resolving the authorization issue. If resolved, the original API request will be re-run, along with any other authorization-failing API requests that had been automatically held in a queue while the resolution was being attempted. If rejected, the APIAuthorizationFailure
event will be broadcast, along with an optional message sent from the function.
The function will have access to the data
, options
, and status
values from the initial unauthorized request, as defined in the Promise for HTTP Alias Methods. Custom 401
handling will be disabled for any requests made in this function, to prevent the possibility of infinite authorization loops.
apiService.unauthorizedInterrupt = function ( data, options, status )
{
var deferred = $q.defer();
// TODO: Attempt to resolve authorization issue, then resolve() or reject() promise
return deferred.promise;
};
Any re-run requests following a successful authorization resolution that still end up returning a 401
will broadcast the APIRequestUnauthorized
event and not attempt a second resolution.
loginPath
String | Default: null
Redirecting to a login page is outside of the scope of this service's intended function, but you can provide your login path to make sure that the 401
-handling functions of this service (unauthorizedInterrupt
& APIRequestUnauthorized
) do not activate when making requests on the login page, where a 401
is a semantically valid response to invalid credentials.
The supplied path will be compared to the value of $location.path()
.
loginRoutes
String or Array | Default: null
Supply a String or Array of Strings that correspond to API routes that should be excluded from the 401
-handling functions of this service (unauthorizedInterrupt
& APIRequestUnauthorized
). Similarly to loginPath
, this allows for the handling of a semantically valid 401
response to invalid login credentials. Useful when your login mechanism isn't siloed to a single page.
The supplied route or routes will be compared to the path
value passed into the HTTP alias method, without prepending rootPath
.
Methods
extendHeaders( headers )
Will extend the existing headers object, which contains the authorization key.
Arguments
headers
| Object | used as theheaders
parameter in the$http
request
setKey( key )
Sets the key that you will use to authenticate with your API. The key will be assigned to the header value defined via keyName
, or "Authorization"
by default.
Arguments
key
| String | the key to authenticate API requests
getKey()
Returns the current value of API key.
Returns
String | the API key
HTTP Interface
The following methods can be called on an instantiated API
service once it has been injected into your Angular code.
- queryUrl( path, requestData [, options ] )
- $get( path [, requestData ] )
- $post( path, requestData )
- $postFile( path, requestData )
- $put( path, requestData )
- $patch( path, requestData )
- $delete( path )
- repeatRequest( request )
- resetAuthResolution()
Promise for HTTP Alias Methods
queryUrl( path, requestData [, options ] )
Builds a URL from a base path and an object of parameters. This is the method used by $get
.
Arguments
path
| String | an API routerequestData
| Object | an object that will be serialized into a query stringoptions
| Object | options object
transformHumps
| Boolean | set totrue
to apply decamelize
Returns
String | requestData
serialized and append onto path
$get( path [, requestData ] )
Performs an HTTP GET
request on the supplied API route. If requestData
is supplied it will be serialized and appended to the request as a query string.
Arguments
path
| String | an API routerequestData
| Object | an object that will be serialized into a query string
Returns
Object | see Promise for HTTP Alias Methods
$post( path, requestData )
Performs an HTTP POST
request to the supplied API route.
Arguments
path
| String | an API routerequestData
| Object | an object containing the request payload
Returns
Object | see Promise for HTTP Alias Methods
$postFile( path, requestData )
Performs an HTTP POST
request to the supplied API route, sending a single file along as multipart form data. transformHumps
is set to false
for this request type automatically.
Arguments
path
| String | an API routerequestData
| Object | a JavaScriptFormData
object with the file data appended
Returns
Object | see Promise for HTTP Alias Methods
$put( path, requestData )
Performs an HTTP PUT
request to the supplied API route.
Arguments
path
| String | an API routerequestData
| Object | an object containing the request payload
Returns
Object | see Promise for HTTP Alias Methods
$patch( path, requestData )
Performs an HTTP PATCH
request to the supplied API route.
Arguments
path
| String | an API routerequestData
| Object | an object containing the request payload
Returns
Object | see Promise for HTTP Alias Methods
$delete( path )
Performs an HTTP DELETE
request on the supplied API route.
Arguments
path
| String | an API route
Returns
Object | see Promise for HTTP Alias Methods
repeatRequest( request )
Performs a request and resolves/rejects a promise. This is the method used to repeat requests with authentication issues via unauthorizedInterrupt
.
Arguments
request
| Object | contains request specifications and the promise to resolve/reject
method
| String | HTTP method, ex. GET, POST, etc.path
| String | the path of the request being repeatedrequestData
| Object | the body of the request being repeatedpromise
| Promise | the promise returned by the request being repeated
resetAuthResolution()
Resets the service's authorization-resolution state, so further requests won't be queued or re-run as part of a currently ongoing resolution attempt. Can be called by application code in times where a resolution requires the short-circuiting of the service so application logic can take over.
Promise for HTTP Alias Methods
Methods beginning with $
return an Angular promise that resolves upon completion of the API request. The resolve/reject handlers are passed a response object with the following format:
{
data: Object | the response from the $http request,
options: Object | the options that were passed into the $http request,
status: Number | the HTTP status code for the completed request
}
The promise includes a custom $cancel
method:
$cancel( [ message, options, reject ] )
Call to halt the HTTP request while in progress. Unless explicitly told otherwise via reject
, the promise for the request will remain unresolved.
message
| String | a text message to describe the cancellationoptions
| Object | an object to describe the canceled requestreject
| Boolean | if set totrue
, the promise will be rejected with an object with the following format:
{
data: message,
options: options
}
Events
The following events will broadcast on $rootScope
during the API
service's life cycle.
- APIRequestStart
- APIRequestComplete
- APIRequestSuccess
- APIRequestError
- APIRequestUnauthorized
- APIAuthorizationFailure
- APIRequestCanceled
APIRequestStart
Broadcast at the start of any API request.
Listener Arguments
options
| Object | the options that were passed into the$http
request
APIRequestComplete
Broadcast upon the completion of any API request. Not broadcast when a request is canceled using the $cancel
method.
Listener Arguments
options
| Object | the options that were passed into the$http
requestdata
| Object | the response from the$http
requeststatus
| Number | the HTTP status code for the completed request
APIRequestSuccess
Broadcast upon the successful completion of any API request.
Listener Arguments
options
| Object | the options that were passed into the$http
requestdata
| Object | the response from the$http
requeststatus
| Number | the HTTP status code for the completed request
APIRequestError
Broadcast upon the erroneous completion of any API request.
Listener Arguments
options
| Object | the options that were passed into the$http
requestdata
| Object | the response from the$http
requeststatus
| Number | the HTTP status code for the completed request
APIRequestUnauthorized
Broadcast upon the unauthorized (status code 401
) completion of any API request. If an attempt to resolve an authorization issue is made via unauthorizedInterrupt
, this event will only broadcast if a 401
is returned when the initial request is re-run.
Listener Arguments
options
| Object | the options that were passed into the$http
requestdata
| Object | the response from the$http
requeststatus
| Number | the HTTP status code for the completed request
APIAuthorizationFailure
Broadcast upon the failure of the function supplied via unauthorizedInterrupt
to successfully resolve an authorization issue.
Listener Arguments
failure
| String | a message sent from theunauthorizedInterrupt
functionoptions
| Object | the options that were passed into the original$http
request that returned a401
APIRequestCanceled
Broadcast when the $cancel
method is called on an API promise.
Listener Arguments
options
| Object | an object sent when the request was canceledmessage
| String | a message sent when the request was canceled