gund / ng-http-interceptor

Http Interceptor library for Angular
MIT License
104 stars 16 forks source link
angular angular2 angular4 http interceptor typescript

ng-http-interceptor

Http Interceptor library for Angular

Previously was called ng2-http-interceptor

Travis CI Coverage Code Climate Npm Npm Downloads Licence semantic-release

Version 4.x.x supports Angular 5 (ng-http-interceptor@^4.0.0)

Version 3.x.x supports Angular 4 (ng-http-interceptor@^3.0.0)

Version 2.x.x supports Angular 2 (ng-http-interceptor@^2.0.0)

Features

Table of Contents

Prerequisites

This library uses Proxy from ES6 spec so if you need to support browsers that are ES5 compatible include proxy-polyfill.

Library uses tslib (standard Typescript runtime library) so please make sure you have this module installed via npm.

Installation

To install this library, run:

$ npm install ng-http-interceptor --save

Usage

Case #1

Import HttpInterceptorModule to your application module. This will override original Http Service and all requests will be intercepted.

Case #2

Import as HttpInterceptorModule.noOverrideHttp() to keep original Http Service and use InterceptableHttp for requests to be intercepted.

Example use-case

You can use InterceptableHttp for your requests in case #1 and #2 and Http if you chose to override it (case #1 only):

constructor(http: Http, httpInterceptor: HttpInterceptorService) {
    httpInterceptor.request().addInterceptor((data, method) => {
      console.log(method, data);
      return data;
    });

    httpInterceptor.response().addInterceptor((res, method) => {
      return res.do(r => console.log(method, r));
    });

    this.http.get('/')
          .map(r => r.text())
          .subscribe(console.log);
}

In this setup every request and response will be logged to the console. You can also cancel request by returning false value (that coerce to boolean false) from one of registered request interceptors. You can return Observable from request interceptors to do some async job.

You can find in-depth explanation of internal concepts here: https://goo.gl/GU9VWo Also if you want to play with it check this repo. Or check this plnkr demo.

Documentation

All and every interception setup is made by HttpInterceptorService service. Inject this service in place where you want to manage interceptors.

Public API

HttpInterceptorService

HttpInterceptorService: {
    request(url?: string|RegExp): Interceptable,
    response(url?: string|RegExp): Interceptable
}

See src/http/http-interceptor.ts for full reference

Description: Methods will determine when to call interceptor - before request (request()) or after response (response()). You can also specify url filtering (string|RegExp) which will indicate when interceptor must be triggered depending on url. By default all interceptors fall under '/' url key which means every interceptor registered that way will be triggered despite of actual url.

Interceptable

Interceptable: {
    addInterceptor(interceptorFn: Interceptor): Interceptable,
    removeInterceptor(interceptorFn: Interceptor): Interceptable,
    clearInterceptors(interceptorFns?: Interceptor[]): Interceptable
}

See src/http/interceptable.ts for full reference

Description: This object will help you manage interceptors with respect to your selected configuration (url filtering).

Interceptor

Interceptor<T, D> {
  (data: T, method: string, ctx?: any): D;
}

See src/http/interceptable.ts for full reference

Description: This is generic type of interceptor - which is a plain old JavaScript function. You will be dealing with specific one to satisfy it's criteria:

Helpers Functions (since v1.3.0)

There are a bunch of helper functions added to simplify some common work with data array (for ex. getting RequestOptions or even Headers).

getHttpHeadersOrInit()

function getHttpHeadersOrInit(data: any[], method: string): Headers;

See src/http/helpers/getHttpHeadersOrInit.ts for full reference

Description: Gets Headers from data array. If no RequestOptions found - creates it and updates original data array. If no Headers found - creates it and sets to RequestOptions.

Exmaple how to add custom headers to requests:

httpInterceptor.request().addInterceptor((data, method) => {
  const headers = getHttpHeadersOrInit(data, method);
  headers.set('X-Custom-Header', 'value');
  return data;
});

getHttpOptionsAndIdx()

function getHttpOptionsAndIdx(
    data: any[],
    method: string,
    alwaysOriginal?: boolean
): {
    options: RequestOptions;
    idx: number;
};

See src/http/helpers/getHttpOptionsAndIdx.ts for full reference

Description: Gets RequestOptions and it's index location in data array. If no options found and alwaysOriginal = false - creates new RequestOptions but does NOT set it back on data array.

getHttpOptions()

function getHttpOptions(
    data: any[],
    method: string,
    alwaysOriginal?: boolean): RequestOptions;

See src/http/helpers/getHttpOptions.ts for full reference

Description: Gets http RequestOptions from data array. If no options found and alwaysOriginal = false - returns new RequestOptions but does NOT set it back on data array.

getHttpOptionsIdx()

function getHttpOptionsIdx(method: string): number;

See src/http/helpers/getHttpOptionsIdx.ts for full reference

Description: Gets index of RequestOptions in http data array for specified method.

Development

To generate all *.js, *.js.map, *.d.ts and *.metadata.json files:

$ npm run build

To lint all *.ts files:

$ npm run lint

To run unit tests:

$ npm test

License

MIT © Alex Malkevich