npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vokal-ng-api

v8.0.0

Published

Vokal's common Angular 1.x API service

Downloads

3

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:

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
  1. headers | Object | used as the headers 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
  1. 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.

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
  1. path | String | an API route
  2. requestData | Object | an object that will be serialized into a query string
  3. options | Object | options object
  • transformHumps | Boolean | set to true 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
  1. path | String | an API route
  2. requestData | 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
  1. path | String | an API route
  2. requestData | 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
  1. path | String | an API route
  2. requestData | Object | a JavaScript FormData 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
  1. path | String | an API route
  2. requestData | 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
  1. path | String | an API route
  2. requestData | 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
  1. 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
  1. 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 repeated
  • requestData | Object | the body of the request being repeated
  • promise | 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.

  1. message | String | a text message to describe the cancellation
  2. options | Object | an object to describe the canceled request
  3. reject | Boolean | if set to true, 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

Broadcast at the start of any API request.

Listener Arguments
  1. 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
  1. options | Object | the options that were passed into the $http request
  2. data | Object | the response from the $http request
  3. status | Number | the HTTP status code for the completed request

APIRequestSuccess

Broadcast upon the successful completion of any API request.

Listener Arguments
  1. options | Object | the options that were passed into the $http request
  2. data | Object | the response from the $http request
  3. status | Number | the HTTP status code for the completed request

APIRequestError

Broadcast upon the erroneous completion of any API request.

Listener Arguments
  1. options | Object | the options that were passed into the $http request
  2. data | Object | the response from the $http request
  3. status | 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
  1. options | Object | the options that were passed into the $http request
  2. data | Object | the response from the $http request
  3. status | 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
  1. failure | String | a message sent from the unauthorizedInterrupt function
  2. options | Object | the options that were passed into the original $http request that returned a 401

APIRequestCanceled

Broadcast when the $cancel method is called on an API promise.

Listener Arguments
  1. options | Object | an object sent when the request was canceled
  2. message | String | a message sent when the request was canceled