From 1cce5835b9279d16d281be1dd8342a5afcdc6935 Mon Sep 17 00:00:00 2001 From: Ashok Koyi Date: Thu, 19 Jan 2017 00:59:30 +0530 Subject: [PATCH 1/8] v2.0.0 --- .editorconfig | 9 + .gitignore | 7 +- .vscode/tasks.json | 11 + index.d.ts | 12 +- index.js | 4 +- lib/intercepted-request.d.ts | 6 - lib/intercepted-request.js | 2 - lib/intercepted-request.js.map | 1 - lib/intercepted-response.d.ts | 7 - lib/intercepted-response.js | 2 - lib/intercepted-response.js.map | 1 - lib/interceptor-options.d.ts | 4 - lib/interceptor-options.js | 2 - lib/interceptor-options.js.map | 1 - lib/interceptor-provider.d.ts | 2 - lib/interceptor-provider.js | 46 -- lib/interceptor-provider.js.map | 1 - lib/interceptor-service.d.ts | 47 -- lib/interceptor-service.js | 248 ------- lib/interceptor-service.js.map | 1 - lib/interceptor.d.ts | 7 - lib/interceptor.js | 2 - lib/interceptor.js.map | 1 - package.json | 29 +- src/intercepted-request.ts | 7 - src/intercepted-response.ts | 8 - src/interceptor-options.ts | 5 - src/interceptor-provider.ts | 77 +- src/interceptor-request-options-args.ts | 8 + src/interceptor-request-wrapper-builder.ts | 66 ++ src/interceptor-request-wrapper.ts | 73 ++ src/interceptor-response-wrapper-builder.ts | 73 ++ src/interceptor-response-wrapper.ts | 127 ++++ src/interceptor-service.ts | 761 +++++++++++++------- src/interceptor-utils.ts | 30 + src/interceptor.ts | 61 +- src/real-response-observable-transformer.ts | 14 + src/tsconfig.json | 18 +- yarn.lock | 34 +- 39 files changed, 1072 insertions(+), 743 deletions(-) create mode 100644 .editorconfig create mode 100644 .vscode/tasks.json delete mode 100644 lib/intercepted-request.d.ts delete mode 100644 lib/intercepted-request.js delete mode 100644 lib/intercepted-request.js.map delete mode 100644 lib/intercepted-response.d.ts delete mode 100644 lib/intercepted-response.js delete mode 100644 lib/intercepted-response.js.map delete mode 100644 lib/interceptor-options.d.ts delete mode 100644 lib/interceptor-options.js delete mode 100644 lib/interceptor-options.js.map delete mode 100644 lib/interceptor-provider.d.ts delete mode 100644 lib/interceptor-provider.js delete mode 100644 lib/interceptor-provider.js.map delete mode 100644 lib/interceptor-service.d.ts delete mode 100644 lib/interceptor-service.js delete mode 100644 lib/interceptor-service.js.map delete mode 100644 lib/interceptor.d.ts delete mode 100644 lib/interceptor.js delete mode 100644 lib/interceptor.js.map delete mode 100644 src/intercepted-request.ts delete mode 100644 src/intercepted-response.ts delete mode 100644 src/interceptor-options.ts create mode 100644 src/interceptor-request-options-args.ts create mode 100644 src/interceptor-request-wrapper-builder.ts create mode 100644 src/interceptor-request-wrapper.ts create mode 100644 src/interceptor-response-wrapper-builder.ts create mode 100644 src/interceptor-response-wrapper.ts create mode 100644 src/interceptor-utils.ts create mode 100644 src/real-response-observable-transformer.ts diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..cb8b48c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +# Editor configuration, see http://editorconfig.org +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true \ No newline at end of file diff --git a/.gitignore b/.gitignore index 93f1361..0d78a3c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ -node_modules -npm-debug.log +lib/ +node_modules/ +*.log +yarn.lock +*.js diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..7e6aa8a --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,11 @@ +{ + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "0.1.0", + "command": "tsc", + "isShellCommand": true, + "args": ["-w", "-p", "./src"], + "showOutput": "silent", + "isWatching": true, + "problemMatcher": "$tsc-watch" +} diff --git a/index.d.ts b/index.d.ts index c754168..34fb76f 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,6 +1,6 @@ -export { InterceptedRequest } from "./lib/intercepted-request"; -export { InterceptedResponse } from "./lib/intercepted-response"; -export { InterceptorOptions } from "./lib/interceptor-options"; -export { InterceptorService } from "./lib/interceptor-service"; -export { provideInterceptorService } from "./lib/interceptor-provider"; -export { Interceptor } from "./lib/interceptor"; +// export { InterceptedRequest } from "./lib/intercepted-request"; +// export { InterceptedResponse } from "./lib/intercepted-response"; +// export { InterceptorOptions } from "./lib/interceptor-options"; +// export { InterceptorService } from "./lib/interceptor-service"; +// export { provideInterceptorService } from "./lib/interceptor-provider"; +// export { Interceptor } from "./lib/interceptor"; diff --git a/index.js b/index.js index feb2f70..95914af 100644 --- a/index.js +++ b/index.js @@ -1,2 +1,2 @@ -exports.InterceptorService = require('./lib/interceptor-service').InterceptorService; -exports.provideInterceptorService = require('./lib/interceptor-provider').provideInterceptorService; +// exports.InterceptorService = require('./lib/interceptor-service').InterceptorService; +// exports.provideInterceptorService = require('./lib/interceptor-provider').provideInterceptorService; diff --git a/lib/intercepted-request.d.ts b/lib/intercepted-request.d.ts deleted file mode 100644 index 46e1c19..0000000 --- a/lib/intercepted-request.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { RequestOptionsArgs } from '@angular/http'; -export interface InterceptedRequest { - url: string; - options?: RequestOptionsArgs; - interceptorOptions?: any; -} diff --git a/lib/intercepted-request.js b/lib/intercepted-request.js deleted file mode 100644 index 44eeca2..0000000 --- a/lib/intercepted-request.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=intercepted-request.js.map \ No newline at end of file diff --git a/lib/intercepted-request.js.map b/lib/intercepted-request.js.map deleted file mode 100644 index cbe7305..0000000 --- a/lib/intercepted-request.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"intercepted-request.js","sourceRoot":"","sources":["../src/intercepted-request.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/intercepted-response.d.ts b/lib/intercepted-response.d.ts deleted file mode 100644 index 047733e..0000000 --- a/lib/intercepted-response.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { Response } from '@angular/http'; -export interface InterceptedResponse { - response: Response; - intercepted?: Boolean; - interceptorStep?: number; - interceptorOptions?: any; -} diff --git a/lib/intercepted-response.js b/lib/intercepted-response.js deleted file mode 100644 index db6f93a..0000000 --- a/lib/intercepted-response.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=intercepted-response.js.map \ No newline at end of file diff --git a/lib/intercepted-response.js.map b/lib/intercepted-response.js.map deleted file mode 100644 index 1acf43b..0000000 --- a/lib/intercepted-response.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"intercepted-response.js","sourceRoot":"","sources":["../src/intercepted-response.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/interceptor-options.d.ts b/lib/interceptor-options.d.ts deleted file mode 100644 index 5a0e5b8..0000000 --- a/lib/interceptor-options.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { RequestOptionsArgs } from '@angular/http'; -export interface InterceptorOptions extends RequestOptionsArgs { - interceptorOptions?: any; -} diff --git a/lib/interceptor-options.js b/lib/interceptor-options.js deleted file mode 100644 index 73a1cfd..0000000 --- a/lib/interceptor-options.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=interceptor-options.js.map \ No newline at end of file diff --git a/lib/interceptor-options.js.map b/lib/interceptor-options.js.map deleted file mode 100644 index b5e03bc..0000000 --- a/lib/interceptor-options.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"interceptor-options.js","sourceRoot":"","sources":["../src/interceptor-options.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/interceptor-provider.d.ts b/lib/interceptor-provider.d.ts deleted file mode 100644 index 46c98e0..0000000 --- a/lib/interceptor-provider.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { FactoryProvider } from '@angular/core'; -export declare function provideInterceptorService(interceptors: any[]): FactoryProvider; diff --git a/lib/interceptor-provider.js b/lib/interceptor-provider.js deleted file mode 100644 index db6a6d1..0000000 --- a/lib/interceptor-provider.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -var http_1 = require("@angular/http"); -var interceptor_service_1 = require("./interceptor-service"); -function provideInterceptorService(interceptors) { - var deps = [ - http_1.XHRBackend, - http_1.RequestOptions - ]; - interceptors = interceptors.map(function (interceptor) { - if (typeof interceptor == "function") { - deps.push(interceptor); - return { - useValue: false, - index: deps.length - 1 - }; - } - else { - return { - useValue: interceptor - }; - } - }); - return { - provide: interceptor_service_1.InterceptorService, - useFactory: function () { - var injectedServices = arguments; - var xhrBackend = injectedServices[0]; - var requestOptions = injectedServices[1]; - var service = new interceptor_service_1.InterceptorService(xhrBackend, requestOptions); - interceptors.forEach(function (interceptor) { - if (interceptor.useValue) { - service.addInterceptor(interceptor.useValue); - } - else { - var value = injectedServices[interceptor.index]; - service.addInterceptor(value); - } - }); - return service; - }, - deps: deps, - multi: false - }; -} -exports.provideInterceptorService = provideInterceptorService; -//# sourceMappingURL=interceptor-provider.js.map \ No newline at end of file diff --git a/lib/interceptor-provider.js.map b/lib/interceptor-provider.js.map deleted file mode 100644 index b6c5dee..0000000 --- a/lib/interceptor-provider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"interceptor-provider.js","sourceRoot":"","sources":["../src/interceptor-provider.ts"],"names":[],"mappings":";AACA,sCAA2D;AAC3D,6DAA2D;AAE3D,mCAA0C,YAAkB;IAC3D,IAAI,IAAI,GAAS;QAChB,iBAAU;QACV,qBAAc;KACd,CAAC;IAEF,YAAY,GAAG,YAAY,CAAC,GAAG,CAAC,UAAC,WAAe;QAC/C,EAAE,CAAA,CAAC,OAAO,WAAW,IAAI,UAAU,CAAC,CAAA,CAAC;YACpC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACvB,MAAM,CAAC;gBACN,QAAQ,EAAE,KAAK;gBACf,KAAK,EAAE,IAAI,CAAC,MAAM,GAAC,CAAC;aACpB,CAAA;QACF,CAAC;QAAA,IAAI,CAAA,CAAC;YACL,MAAM,CAAC;gBACN,QAAQ,EAAE,WAAW;aACrB,CAAA;QACF,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC;QACN,OAAO,EAAE,wCAAkB;QAC3B,UAAU,EAAE;YACX,IAAI,gBAAgB,GAAG,SAAS,CAAC;YACjC,IAAI,UAAU,GAAc,gBAAgB,CAAC,CAAC,CAAC,CAAC;YAChD,IAAI,cAAc,GAAkB,gBAAgB,CAAC,CAAC,CAAC,CAAC;YAExD,IAAI,OAAO,GAAG,IAAI,wCAAkB,CAAC,UAAU,EAAE,cAAc,CAAC,CAAC;YACjE,YAAY,CAAC,OAAO,CAAC,UAAC,WAAW;gBAChC,EAAE,CAAA,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAA,CAAC;oBACxB,OAAO,CAAC,cAAc,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;gBAC9C,CAAC;gBAAA,IAAI,CAAA,CAAC;oBACL,IAAI,KAAK,GAAG,gBAAgB,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;oBAChD,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;gBAC/B,CAAC;YACF,CAAC,CAAC,CAAC;YACH,MAAM,CAAC,OAAO,CAAC;QAChB,CAAC;QACD,IAAI,EAAE,IAAI;QACV,KAAK,EAAE,KAAK;KACZ,CAAA;AACF,CAAC;AAzCD,8DAyCC"} \ No newline at end of file diff --git a/lib/interceptor-service.d.ts b/lib/interceptor-service.d.ts deleted file mode 100644 index 73b3f8a..0000000 --- a/lib/interceptor-service.d.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { ConnectionBackend, Http, Request, Response, RequestOptions } from '@angular/http'; -import { Observable } from 'rxjs/Rx'; -import { InterceptorOptions } from "./interceptor-options"; -import { Interceptor } from "./interceptor"; -export declare class InterceptorService extends Http { - private interceptors; - constructor(backend: ConnectionBackend, defaultOptions: RequestOptions); - /** - Before interceptor - patata - */ - addInterceptor(interceptor: Interceptor): void; - /** Parent overrides **/ - private httpRequest(request); - request(url: string | Request, options?: InterceptorOptions): Observable; - /** - * Performs a request with `get` http method. - */ - get(url: string, options?: InterceptorOptions): Observable; - /** - * Performs a request with `post` http method. - */ - post(url: string, body: any, options?: InterceptorOptions): Observable; - /** - * Performs a request with `put` http method. - */ - put(url: string, body: any, options?: InterceptorOptions): Observable; - /** - * Performs a request with `delete` http method. - */ - delete(url: string, options?: InterceptorOptions): Observable; - /** - * Performs a request with `patch` http method. - */ - patch(url: string, body: any, options?: InterceptorOptions): Observable; - /** - * Performs a request with `head` http method. - */ - head(url: string, options?: InterceptorOptions): Observable; - /** - * Performs a request with `options` http method. - */ - options(url: string, options?: InterceptorOptions): Observable; - /** Private functions **/ - private runBeforeInterceptors(params); - private runAfterInterceptors(response, startOn); -} diff --git a/lib/interceptor-service.js b/lib/interceptor-service.js deleted file mode 100644 index 2b67535..0000000 --- a/lib/interceptor-service.js +++ /dev/null @@ -1,248 +0,0 @@ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var http_1 = require("@angular/http"); -var Rx_1 = require("rxjs/Rx"); -var InterceptorService = (function (_super) { - __extends(InterceptorService, _super); - function InterceptorService(backend, defaultOptions) { - var _this = _super.call(this, backend, defaultOptions) || this; - _this.interceptors = []; - return _this; - } - /** - Before interceptor - patata - */ - InterceptorService.prototype.addInterceptor = function (interceptor) { - this.interceptors.push(interceptor); - }; - /** Parent overrides **/ - InterceptorService.prototype.httpRequest = function (request) { - var _this = this; - request.options = request.options || {}; - request.options.headers = request.options.headers || new http_1.Headers(); - return this.runBeforeInterceptors(request) - .flatMap(function (value, index) { - // We return an observable that merges the result of the request plus the interceptorOptions we need - return Rx_1.Observable.zip(_super.prototype.request.call(_this, value.url, value.options), Rx_1.Observable.of(value.interceptorOptions), function (response, options) { - return { - response: response, - interceptorOptions: options - }; - }).catch(function (err) { - return Rx_1.Observable.of({ - response: err, - interceptorOptions: value.interceptorOptions || {} - }); - }); - }) - .catch(function (err) { - // If it's a cancel, create a fake response and pass it to next interceptors - if (err.error == "cancelled") { - var response = new http_1.ResponseOptions({ - body: null, - status: 0, - statusText: "intercepted", - headers: new http_1.Headers() - }); - return Rx_1.Observable.of({ - response: new http_1.Response(response), - intercepted: true, - interceptorStep: err.position, - interceptorOptions: err.interceptorOptions - }); - } - else { - } - }) - .flatMap(function (value, index) { - var startOn = (value.intercepted) ? value.interceptorStep : _this.interceptors.length - 1; - return _this.runAfterInterceptors(value, startOn); - }) - .flatMap(function (value, index) { - return Rx_1.Observable.of(value.response); - }) - .flatMap(function (value, index) { - if (!value.ok) - return Rx_1.Observable.throw(value); - return Rx_1.Observable.of(value); - }); - }; - InterceptorService.prototype.request = function (url, options) { - options = options || {}; - var responseObservable; - if (typeof url === 'string') { - responseObservable = this.httpRequest({ - url: url, - options: options, - interceptorOptions: options.interceptorOptions || {} - }); - } - else if (url instanceof http_1.Request) { - var request = url; - responseObservable = this.httpRequest({ - url: request.url, - options: { - method: request.method, - headers: request.headers, - url: request.url, - withCredentials: request.withCredentials, - responseType: request.responseType, - body: request.getBody() - }, - interceptorOptions: options.interceptorOptions || {} - }); - } - else { - throw new Error('First argument must be a url string or Request instance.'); - } - return responseObservable; - }; - /** - * Performs a request with `get` http method. - */ - InterceptorService.prototype.get = function (url, options) { - options = options || {}; - options.method = options.method || http_1.RequestMethod.Get; - options.url = options.url || url; - return this.request(url, options); - }; - /** - * Performs a request with `post` http method. - */ - InterceptorService.prototype.post = function (url, body, options) { - options = options || {}; - options.method = options.method || http_1.RequestMethod.Post; - options.url = options.url || url; - options.body = options.body || body; - return this.request(url, options); - }; - /** - * Performs a request with `put` http method. - */ - InterceptorService.prototype.put = function (url, body, options) { - options = options || {}; - options.method = options.method || http_1.RequestMethod.Put; - options.url = options.url || url; - options.body = options.body || body; - return this.request(url, options); - }; - /** - * Performs a request with `delete` http method. - */ - InterceptorService.prototype.delete = function (url, options) { - options = options || {}; - options.method = options.method || http_1.RequestMethod.Delete; - options.url = options.url || url; - return this.request(url, options); - }; - /** - * Performs a request with `patch` http method. - */ - InterceptorService.prototype.patch = function (url, body, options) { - options = options || {}; - options.method = options.method || http_1.RequestMethod.Patch; - options.url = options.url || url; - options.body = options.body || body; - return this.request(url, options); - }; - /** - * Performs a request with `head` http method. - */ - InterceptorService.prototype.head = function (url, options) { - options = options || {}; - options.method = options.method || http_1.RequestMethod.Head; - options.url = options.url || url; - return this.request(url, options); - }; - /** - * Performs a request with `options` http method. - */ - InterceptorService.prototype.options = function (url, options) { - options = options || {}; - options.method = options.method || http_1.RequestMethod.Options; - options.url = options.url || url; - return this.request(url, options); - }; - /** Private functions **/ - InterceptorService.prototype.runBeforeInterceptors = function (params) { - var ret = Rx_1.Observable.of(params); - var _loop_1 = function (i) { - var bf = this_1.interceptors[i]; - if (!bf.interceptBefore) - return "continue"; - ret = ret.flatMap(function (value, index) { - var newObs; - var res = null; - try { - res = bf.interceptBefore(value); - } - catch (ex) { - console.error(ex); - } - if (!res) - newObs = Rx_1.Observable.of(value); - else if (!(res instanceof Rx_1.Observable)) - newObs = Rx_1.Observable.of(res); - else - newObs = res; - return newObs.catch(function (err, caught) { - if (err == "cancelled") { - return Rx_1.Observable.throw({ - error: "cancelled", - interceptorOptions: params.interceptorOptions, - position: i - }); - } - return Rx_1.Observable.throw({ - error: "unknown", - interceptorOptions: params.interceptorOptions, - err: err - }); - }); - }); - }; - var this_1 = this; - for (var i = 0; i < this.interceptors.length; i++) { - _loop_1(i); - } - return ret; - }; - InterceptorService.prototype.runAfterInterceptors = function (response, startOn) { - var ret = Rx_1.Observable.of(response); - var _loop_2 = function (i) { - var af = this_2.interceptors[i]; - if (!af.interceptAfter) - return "continue"; - ret = ret.flatMap(function (value, index) { - var newObs; - var res = null; - try { - res = af.interceptAfter(value); - } - catch (ex) { - console.error(ex); - } - if (!res) - newObs = Rx_1.Observable.of(value); - else if (!(res instanceof Rx_1.Observable)) - newObs = Rx_1.Observable.of(res); - else - newObs = res; - return newObs; - }); - }; - var this_2 = this; - for (var i = startOn; i >= 0; i--) { - _loop_2(i); - } - return ret; - }; - return InterceptorService; -}(http_1.Http)); -exports.InterceptorService = InterceptorService; -//# sourceMappingURL=interceptor-service.js.map \ No newline at end of file diff --git a/lib/interceptor-service.js.map b/lib/interceptor-service.js.map deleted file mode 100644 index 0382a07..0000000 --- a/lib/interceptor-service.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"interceptor-service.js","sourceRoot":"","sources":["../src/interceptor-service.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/lib/interceptor.d.ts b/lib/interceptor.d.ts deleted file mode 100644 index 4899255..0000000 --- a/lib/interceptor.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { InterceptedRequest } from "./intercepted-request"; -import { InterceptedResponse } from "./intercepted-response"; -import { Observable } from 'rxjs/Rx'; -export interface Interceptor { - interceptBefore?(request: InterceptedRequest): Observable | InterceptedRequest; - interceptAfter?(response: InterceptedResponse): Observable | InterceptedResponse; -} diff --git a/lib/interceptor.js b/lib/interceptor.js deleted file mode 100644 index f7e9cc2..0000000 --- a/lib/interceptor.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=interceptor.js.map \ No newline at end of file diff --git a/lib/interceptor.js.map b/lib/interceptor.js.map deleted file mode 100644 index 26b5b42..0000000 --- a/lib/interceptor.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"interceptor.js","sourceRoot":"","sources":["../src/interceptor.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/package.json b/package.json index 818742d..6f111d2 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,20 @@ { - "name": "ng2-interceptors", - "version": "1.2.4", + "name": "ng-http-interceptor", + "version": "2.0.0", "description": "Angular2 interceptor service implementation", "keywords": [ "Angular 2", + "Http interceptor", "Interceptor" ], "author": { "name": "Víctor Oliva", "email": "olivarra1@gmail.com" }, + "contributors": [{ + "name": "Ashok Koyi", + "url": "http://thekalinga.in" + }], "repository": { "type": "git", "url": "https://github.com/voliva/angular2-interceptors" @@ -20,17 +25,17 @@ "build": "rimraf lib && tsc -p src" }, "peerDependencies": { - "@angular/core": "^2.0.0", - "@angular/http": "^2.0.0", - "rxjs": "5.0.0-beta.12" + "@angular/core": ">=4.0.0-beta.1 <5", + "@angular/http": ">=4.0.0-beta.1 <5", + "rxjs": "^5.0.0" }, "devDependencies": { - "@angular/common": "^2.0.0", - "@angular/core": "^2.0.0", - "@angular/http": "^2.0.0", - "@angular/platform-browser": "^2.0.0", - "rxjs": "^5.0.0-beta.12", - "typescript": "^2.0.3", - "zone.js": "^0.6.21" + "@angular/common": ">=4.0.0-beta.1 <5", + "@angular/core": ">=4.0.0-beta.1 <5", + "@angular/http": ">=4.0.0-beta.1 <5", + "@angular/platform-browser": ">=4.0.0-beta.1 <5", + "rxjs": "^5.0.3", + "typescript": "^2.1.5", + "zone.js": "^0.6.26" } } diff --git a/src/intercepted-request.ts b/src/intercepted-request.ts deleted file mode 100644 index d3ce7a5..0000000 --- a/src/intercepted-request.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { RequestOptionsArgs } from '@angular/http'; - -export interface InterceptedRequest { - url: string, - options?: RequestOptionsArgs, - interceptorOptions?: any -} diff --git a/src/intercepted-response.ts b/src/intercepted-response.ts deleted file mode 100644 index 5f56c85..0000000 --- a/src/intercepted-response.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Response } from '@angular/http'; - -export interface InterceptedResponse { - response: Response, - intercepted?: Boolean, - interceptorStep?: number, - interceptorOptions?: any -} diff --git a/src/interceptor-options.ts b/src/interceptor-options.ts deleted file mode 100644 index f199217..0000000 --- a/src/interceptor-options.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { RequestOptionsArgs } from '@angular/http'; - -export interface InterceptorOptions extends RequestOptionsArgs { - interceptorOptions?: any -} diff --git a/src/interceptor-provider.ts b/src/interceptor-provider.ts index 4089e19..f772293 100644 --- a/src/interceptor-provider.ts +++ b/src/interceptor-provider.ts @@ -1,46 +1,47 @@ import { FactoryProvider } from '@angular/core'; import { XHRBackend, RequestOptions } from '@angular/http'; + import { InterceptorService } from './interceptor-service'; -export function provideInterceptorService(interceptors:any[]):FactoryProvider { - let deps:any[] = [ - XHRBackend, - RequestOptions - ]; +export function provideInterceptorService(interceptors: any[]): FactoryProvider { + let deps: any[] = [ + XHRBackend, + RequestOptions + ]; - interceptors = interceptors.map((interceptor:any) => { - if(typeof interceptor == "function"){ - deps.push(interceptor); - return { - useValue: false, - index: deps.length-1 - } - }else{ - return { - useValue: interceptor - } - } - }); + interceptors = interceptors.map((interceptor: any) => { + if (typeof interceptor == "function") { + deps.push(interceptor); + return { + useValue: false, + index: deps.length - 1 + } + } else { + return { + useValue: interceptor + } + } + }); - return { - provide: InterceptorService, - useFactory: function(){ - let injectedServices = arguments; - let xhrBackend:XHRBackend = injectedServices[0]; - let requestOptions:RequestOptions = injectedServices[1]; + return { + provide: InterceptorService, + useFactory: function () { + let injectedServices = arguments; + let xhrBackend: XHRBackend = injectedServices[0]; + let requestOptions: RequestOptions = injectedServices[1]; - let service = new InterceptorService(xhrBackend, requestOptions); - interceptors.forEach((interceptor) => { - if(interceptor.useValue){ - service.addInterceptor(interceptor.useValue); - }else{ - let value = injectedServices[interceptor.index]; - service.addInterceptor(value); - } - }); - return service; - }, - deps: deps, - multi: false - } + let service = new InterceptorService(xhrBackend, requestOptions); + interceptors.forEach((interceptor) => { + if (interceptor.useValue) { + service.addInterceptor(interceptor.useValue); + } else { + let value = injectedServices[interceptor.index]; + service.addInterceptor(value); + } + }); + return service; + }, + deps: deps, + multi: false + } } diff --git a/src/interceptor-request-options-args.ts b/src/interceptor-request-options-args.ts new file mode 100644 index 0000000..92dc836 --- /dev/null +++ b/src/interceptor-request-options-args.ts @@ -0,0 +1,8 @@ +import { RequestOptionsArgs } from '@angular/http'; + +/** + * Adds additional data required to be used by the interceptors along the chain + */ +export interface InterceptorRequestOptionsArgs extends RequestOptionsArgs { + sharedData?: any +} diff --git a/src/interceptor-request-wrapper-builder.ts b/src/interceptor-request-wrapper-builder.ts new file mode 100644 index 0000000..d0a6dc2 --- /dev/null +++ b/src/interceptor-request-wrapper-builder.ts @@ -0,0 +1,66 @@ +import { RequestOptionsArgs } from '@angular/http/src/interfaces'; +import { resolveReflectiveProviders } from '@angular/core/src/di/reflective_provider'; +import { reflector } from '@angular/platform-browser/src/private_import_core'; +import { Request, Response } from '@angular/http'; + +import { InterceptorRequestWrapper } from "./interceptor-request-wrapper"; +import { InterceptorUtils } from './interceptor-utils'; + +/** + * Utility builder for creating a new instance of InterceptorRequestWrapper + * Use InterceptorRequestWrapperBuilder.new() to instantiate the builder + */ +export class InterceptorRequestWrapperBuilder { + + protected _url: string | Request; + protected _options?: RequestOptionsArgs; + protected _sharedData?: any; + protected _shortCircuitAtCurrentStep?: boolean; + protected _alsoForceRequestCompletion?: boolean; + protected _alreadyShortCircuited?: boolean; + protected _shortCircuitTriggeredBy?: number; + protected _err?: any; + protected _errEncounteredAt?: number; + + /** + * Use InterceptorResponseBuilder.new() to instantiate the builder + */ + protected constructor() { } + + static new(requestWrapper: InterceptorRequestWrapper): InterceptorRequestWrapperBuilder { + const builder = new InterceptorRequestWrapperBuilder(); + InterceptorUtils.assign(builder, requestWrapper); + return builder; + } + + url(url: string | Request): InterceptorRequestWrapperBuilder { + this._url = url; + return this; + } + + options(options: RequestOptionsArgs): InterceptorRequestWrapperBuilder { + this._options = options; + return this; + } + + sharedData(sharedData: any): InterceptorRequestWrapperBuilder { + this._sharedData = sharedData; + return this; + } + + shortCircuitAtCurrentStep(shortCircuitAtCurrentStep: boolean): InterceptorRequestWrapperBuilder { + this._shortCircuitAtCurrentStep = shortCircuitAtCurrentStep; + return this; + } + + alsoForceRequestCompletion(alsoForceRequestCompletion: boolean): InterceptorRequestWrapperBuilder { + this._alsoForceRequestCompletion = alsoForceRequestCompletion; + return this; + } + + build(): InterceptorRequestWrapper { + this._sharedData = this._sharedData || {}; + return new InterceptorRequestWrapper(this); + } + +} diff --git a/src/interceptor-request-wrapper.ts b/src/interceptor-request-wrapper.ts new file mode 100644 index 0000000..9269281 --- /dev/null +++ b/src/interceptor-request-wrapper.ts @@ -0,0 +1,73 @@ +import { Request, RequestOptionsArgs } from '@angular/http'; + +import { InterceptorRequestWrapperBuilder } from './interceptor-request-wrapper-builder'; +import { InterceptorUtils } from './interceptor-utils'; + +export class InterceptorRequestWrapper { + + constructor(builder: InterceptorRequestWrapperBuilder) { + InterceptorUtils.assign(this, builder); + } + + /** + * url which will be cascaded to the final {@code Http} call + */ + protected _url: string | Request; + + /** + * Request options to be passed to the final {@code Http} call + */ + protected _options?: RequestOptionsArgs; + + /** + * Data that gets shared between all interceptors; across request & response cycles
+ * i.e before interceptor 1, before interceptor 2, actual http call, after interceptor 2, after interceptor 1
+ * Data should accumulated on the same shared state; so be cautious & always make sure that you do neccessary checks such as ${@code sharedData || {}} + */ + protected _sharedData?: any; + + /** + *

Indicates that subsequent interceptors in the interceptor chain along with actual http call to be skipped & proceed with onShortcuit(..)/Observable.complete().

+ *

If {@code alsoForceRequestCompletion} is set true to true, the interceptor chain would invoke onCompleted() on to the subscriber, else onShortcuit(..) method would be invoked on the interceptors whose beforeIntercept(..) was called prior to short circuit, in the reverse order

+ */ + protected _shortCircuitAtCurrentStep?: boolean; + + /** + * Flag to inform interceptor service to skip all futher steps in the interceptor chain & invoke onCompleted() on the subscriber + */ + protected _alsoForceRequestCompletion?: boolean; + + /** + * Indicates that the skip was performed by a ancetor intercetor in the chain, not the last interceptor + */ + protected _alreadyShortCircuited?: boolean; + + /** + * Represents the index of the interceptor step that triggered the short circuit. This value is zero indexed, meaning, if first interceptor in the chain has shorted the circuit, this value will be 0 + */ + protected _shortCircuitTriggeredBy?: number; + + /** + * Any error encountered during processing + */ + protected _err?: any; + + /** + * Index of the interceptor that raise err; This value is zero indexed, meaning, if first interceptor throws an err before http request is sent; this value will be 0 + * If error occurs in the actual http request, the value would be set to `interceptors.length` + */ + protected _errEncounteredAt?: number; + + get url(): string | Request { + return this._url; + } + + get options(): RequestOptionsArgs { + return this._options; + } + + get sharedData(): any { + return this._sharedData; + } + +} diff --git a/src/interceptor-response-wrapper-builder.ts b/src/interceptor-response-wrapper-builder.ts new file mode 100644 index 0000000..ccd57aa --- /dev/null +++ b/src/interceptor-response-wrapper-builder.ts @@ -0,0 +1,73 @@ +import { RequestOptionsArgs } from '@angular/http/src/interfaces'; +import { resolveReflectiveProviders } from '@angular/core/src/di/reflective_provider'; +import { reflector } from '@angular/platform-browser/src/private_import_core'; +import { Request, Response } from '@angular/http'; + +import { InterceptorRequestOptionsArgs } from './interceptor-request-options-args'; +import { InterceptorResponseWrapper } from './interceptor-response-wrapper'; +import { InterceptorUtils } from './interceptor-utils'; + +/** + * Utility builder for creating a new instance of InterceptorResponseWrapper + * Use InterceptorResponseBuilder.new() to instantiate the builder + */ +export class InterceptorResponseWrapperBuilder { + + protected _url: string | Request; + protected _options?: RequestOptionsArgs | InterceptorRequestOptionsArgs; + protected _response: Response; + protected _sharedData?: any; + protected _shortCircuitTriggeredBy?: number; + protected _forceReturnResponse?: boolean; + protected _forceRequestCompletion?: boolean; + protected _responseGeneratedByShortCircuitHandler?: boolean; + protected _err?: any; + protected _errEncounteredAt?: number; + protected _errEncounteredInRequestCycle?: boolean; + + /** + * Use InterceptorResponseBuilder.new() to instantiate the builder + */ + protected constructor() { } + + static new(response: Response | InterceptorResponseWrapper): InterceptorResponseWrapperBuilder { + const builder = new InterceptorResponseWrapperBuilder(); + if (response instanceof Response) { + builder._response = response; + } else if (response) { + InterceptorUtils.assign(builder, response); + } + return builder; + } + + response(response: Response): InterceptorResponseWrapperBuilder { + this._response = response; + return this; + } + + sharedData(sharedData: any): InterceptorResponseWrapperBuilder { + this._sharedData = sharedData; + return this; + } + + forceReturnResponse(forceReturnResponse: boolean): InterceptorResponseWrapperBuilder { + this._forceReturnResponse = forceReturnResponse; + return this; + } + + forceRequestCompletion(forceRequestCompletion: boolean): InterceptorResponseWrapperBuilder { + this._forceRequestCompletion = forceRequestCompletion; + return this; + } + + err(err: any): InterceptorResponseWrapperBuilder { + this._err = err; + return this; + } + + build(): InterceptorResponseWrapper { + this._sharedData = this._sharedData || {}; + return new InterceptorResponseWrapper(this); + } + +} diff --git a/src/interceptor-response-wrapper.ts b/src/interceptor-response-wrapper.ts new file mode 100644 index 0000000..3468dfe --- /dev/null +++ b/src/interceptor-response-wrapper.ts @@ -0,0 +1,127 @@ +import { Request, Response } from '@angular/http'; +import { RequestOptionsArgs } from '@angular/http/src/interfaces'; + +import { InterceptorRequestOptionsArgs } from './interceptor-request-options-args'; +import { InterceptorResponseWrapperBuilder } from './interceptor-response-wrapper-builder'; +import { InterceptorUtils } from './interceptor-utils'; + +export class InterceptorResponseWrapper { + + constructor(builder: InterceptorResponseWrapperBuilder) { + InterceptorUtils.assign(this, builder); + } + + /** + * url which will be cascaded to the final {@code Http} call + */ + protected _url: string | Request; + + /** + * Request options to be passed to the final {@code Http} call + */ + protected _options?: RequestOptionsArgs | InterceptorRequestOptionsArgs; + + /** + * Response that gets cascaded to the caller + */ + protected _response: Response; + + /** + * Data that gets shared between all interceptors; across request & response cycles
+ * i.e before interceptor 1, before interceptor 2, actual http call, after interceptor 2, after interceptor 1
+ * Data should accumulated on the same shared state; so be cautious & always make sure that you do neccessary checks such as ${@code sharedData || {}} + */ + protected _sharedData?: any; + + /** + * Indicates the steps at which the request was cancelled; This value is zero indexed, meaning, if first interceptor has ask for skipping subsequent steps, this value will be 0 + */ + protected _shortCircuitTriggeredBy?: number; + + /** + * Flag to inform interceptor service to skip all futher steps in the interceptor chain & return the {@code response} to the subscriber + * If the response wrapper contains response, the response would be sent to `next` callback method on the subscriber + * If the response is empty & `err` is set, the err would be thrown to the subscriber + * If the response is empty & `shortCircuitTriggeredBy` is set, an err would be thrown to the subscriber + */ + protected _forceReturnResponse?: boolean; + + /** + * Flag to inform interceptor service to skip all futher steps in the interceptor chain & would send complete event to the subscriber + */ + protected _forceRequestCompletion?: boolean; + + /** + * Indicates that the response did not get generated by the final step (the native http request), but rather by a onSkipped(..) + */ + protected _responseGeneratedByShortCircuitHandler?: boolean; + + /** + * Any error encountered during processing + */ + protected _err?: any; + + /** + * Index of the interceptor that raise err; This value is zero indexed, meaning, if first interceptor throws an error before http request is sent; this value will be 0 + * If error occurs during the actual http request, the value would be set to `interceptors.length` + */ + protected _errEncounteredAt?: number; + + /** + * Flag indicating whether the error occurred in post response/prior to getting response + */ + protected _errEncounteredInRequestCycle?: boolean; + + get response(): Response { + return this._response; + } + + get sharedData(): any { + return this._sharedData; + } + + get shortCircuitTriggeredBy(): number { + return this._shortCircuitTriggeredBy; + } + + get forceReturnResponse(): boolean { + return this._forceReturnResponse; + } + + get forceRequestCompletion(): boolean { + return this._forceRequestCompletion; + } + + get responseGeneratedByShortCircuitHandler(): boolean { + return this._responseGeneratedByShortCircuitHandler; + } + + get err(): any { + return this._err; + } + + get errEncounteredAt(): number { + return this._errEncounteredAt; + } + + get errEncounteredInRequestCycle(): boolean { + return this._errEncounteredInRequestCycle; + } + + get responseGeneratedByErrHandler(): boolean { + return !!this._err && !!this._response; + } + + isShortCircuited(): boolean { + return this._shortCircuitTriggeredBy !== undefined; + } + + circuitShortedByMe(currentStep: number): boolean { + return this.isShortCircuited() && this._shortCircuitTriggeredBy === currentStep; + } + + errThrownByMe(currentStep: number): boolean { + return this._errEncounteredAt && this._errEncounteredAt === currentStep; + } + +} diff --git a/src/interceptor-service.ts b/src/interceptor-service.ts index 5884703..69b1424 100644 --- a/src/interceptor-service.ts +++ b/src/interceptor-service.ts @@ -1,258 +1,517 @@ import { - ConnectionBackend, - Headers, - Http, - Request, - Response, - ResponseOptions, - RequestMethod, - RequestOptions + ConnectionBackend, + Headers, + Http, + Request, + Response, + ResponseOptions, + RequestMethod, + RequestOptions } from '@angular/http'; +import { RequestOptionsArgs } from '@angular/http/src/interfaces'; + import { Observable, Observer } from 'rxjs/Rx'; import { ErrorObservable } from 'rxjs/observable/ErrorObservable'; -import { InterceptedRequest } from "./intercepted-request"; -import { InterceptedResponse } from "./intercepted-response"; -import { InterceptorOptions } from "./interceptor-options"; -import { Interceptor } from "./interceptor"; +import { InterceptorRequestWrapper } from './interceptor-request-wrapper'; +import { InterceptorResponseWrapper } from './interceptor-response-wrapper'; +import { Interceptor } from './interceptor'; +import { InterceptorRequestOptionsArgs } from './interceptor-request-options-args'; +import { InterceptorRequestWrapperBuilder } from './interceptor-request-wrapper-builder'; +import { InterceptorResponseWrapperBuilder } from './interceptor-response-wrapper-builder'; +import { InterceptorUtils } from './interceptor-utils'; +import { RealResponseObservableTransformer } from './real-response-observable-transformer'; + +import './object-assign-polyfill'; + +/** + * Wrapper around native angular `Http` service. + * Allows you to add `Interceptor`s that lets you do + * 1. Transform request before it reaches the actual request, such as, add headers transparently + * 2. Transform response, such as stripout the top level object & return the payload (or) raise errors if `response.status` is not `ok` + * 3. To short circuit the request flow based on runtime data + * 4. To selective caching/log request/responses + * 5. Augment the real `Observable` that native angular `http.request(..)` returns + * 6. Store intermediate data that can be shared across the interceptors + * 7. Generate handcrafted response incase of error/base of your runtime decision + * + * The service executes methods in the interceptor chain in the following manner + * 1. For each of the listed interceptor, tranforms the request by invoking `beforeRequest(..)` on each interceptor in the same order they are added + * 2. Invokes native angular `http.request(..)` with the result of last interceptor's `beforeRequest(..)` response + * 3. Invokes `onResponse(..)` on each interceptor in the reverse order they are added + * 4. The response from `onResponse(..)` of the final interceptor in the chain would be sent to subscriber + */ export class InterceptorService extends Http { - private interceptors: Array; - - constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) { - super(backend, defaultOptions); - this.interceptors = []; - } - - /** - Before interceptor - patata - */ - addInterceptor(interceptor: Interceptor) { - this.interceptors.push(interceptor); - } - - /** Parent overrides **/ - private httpRequest(request:InterceptedRequest): Observable { - request.options = request.options || {}; - request.options.headers = request.options.headers || new Headers(); - return this.runBeforeInterceptors(request) - .flatMap((value: InterceptedRequest, index: number) => { - // We return an observable that merges the result of the request plus the interceptorOptions we need - return Observable.zip( - super.request(value.url, value.options), - Observable.of(value.interceptorOptions), - function(response, options) { - return { - response: response, - interceptorOptions: options - } as InterceptedResponse; - } - ).catch((err: any) => { - return Observable.of({ - response: err, - interceptorOptions: value.interceptorOptions || {} - } as InterceptedResponse); - }); - }) - .catch((err: any) => { - // If it's a cancel, create a fake response and pass it to next interceptors - if (err.error == "cancelled") { - var response = new ResponseOptions({ - body: null, - status: 0, - statusText: "intercepted", - headers: new Headers() - }) - return Observable.of({ - response: new Response(response), - intercepted: true, - interceptorStep: err.position, - interceptorOptions: err.interceptorOptions - }); - } else { - // We had an exception in the pipeline... woops? TODO - } - }) - .flatMap((value: InterceptedResponse, index: number) => { - var startOn = (value.intercepted) ? value.interceptorStep : this.interceptors.length - 1; - return this.runAfterInterceptors(value, startOn); - }) - .flatMap((value: InterceptedResponse, index: number) => { - return Observable.of(value.response); - }) - .flatMap((value: Response, index: number) => { - if (!value.ok) - return Observable.throw(value); - - return Observable.of(value); - }); - } - - request(url: string|Request, options?: InterceptorOptions): Observable { - options = options || {}; - let responseObservable: any; - if (typeof url === 'string') { - responseObservable = this.httpRequest({ - url: url, - options: options, - interceptorOptions: options.interceptorOptions || {} - }); - } else if (url instanceof Request) { - let request:Request = url; - responseObservable = this.httpRequest({ - url: request.url, - options: { - method: request.method, - headers: request.headers, - url: request.url, - withCredentials: request.withCredentials, - responseType: request.responseType, - body: request.getBody() - }, - interceptorOptions: options.interceptorOptions || {} - }); - } else { - throw new Error('First argument must be a url string or Request instance.'); - } - return responseObservable; - } - - /** - * Performs a request with `get` http method. - */ - get(url: string, options?: InterceptorOptions): Observable { - options = options || {}; - options.method = options.method || RequestMethod.Get; - options.url = options.url || url; - return this.request(url, options); - } - - /** - * Performs a request with `post` http method. - */ - post(url: string, body: any, options?: InterceptorOptions): Observable { - options = options || {}; - options.method = options.method || RequestMethod.Post; - options.url = options.url || url; - options.body = options.body || body; - return this.request(url, options); - } - - /** - * Performs a request with `put` http method. - */ - put(url: string, body: any, options?: InterceptorOptions): Observable { - options = options || {}; - options.method = options.method || RequestMethod.Put; - options.url = options.url || url; - options.body = options.body || body; - return this.request(url, options); - } - - /** - * Performs a request with `delete` http method. - */ - delete(url: string, options?: InterceptorOptions): Observable { - options = options || {}; - options.method = options.method || RequestMethod.Delete; - options.url = options.url || url; - return this.request(url, options); - } - - /** - * Performs a request with `patch` http method. - */ - patch(url: string, body: any, options?: InterceptorOptions): Observable { - options = options || {}; - options.method = options.method || RequestMethod.Patch; - options.url = options.url || url; - options.body = options.body || body; - return this.request(url, options); - } - - /** - * Performs a request with `head` http method. - */ - head(url: string, options?: InterceptorOptions): Observable { - options = options || {}; - options.method = options.method || RequestMethod.Head; - options.url = options.url || url; - return this.request(url, options); - } - - /** - * Performs a request with `options` http method. - */ - options(url: string, options?: InterceptorOptions): Observable { - options = options || {}; - options.method = options.method || RequestMethod.Options; - options.url = options.url || url; - return this.request(url, options); - } - - /** Private functions **/ - private runBeforeInterceptors(params: InterceptedRequest): Observable { - let ret: Observable = Observable.of(params); - - for (let i = 0; i < this.interceptors.length; i++) { - let bf: Interceptor = this.interceptors[i]; - if (!bf.interceptBefore) continue; - - ret = ret.flatMap((value: InterceptedRequest, index: number) => { - let newObs: Observable; - let res = null; - try { - res = bf.interceptBefore(value); - } catch (ex) { - console.error(ex); - } - if (!res) newObs = Observable.of(value); - else if (!(res instanceof Observable)) newObs = Observable.of(res); - else newObs = res; - - return newObs.catch((err: any, caught: Observable) => { - if (err == "cancelled") { - return >Observable.throw({ - error: "cancelled", - interceptorOptions: params.interceptorOptions, - position: i - }); - } - return >Observable.throw({ - error: "unknown", - interceptorOptions: params.interceptorOptions, - err: err - }); - }); - }); - } - - return ret; - } - - private runAfterInterceptors(response: InterceptedResponse, startOn: number): Observable { - let ret: Observable = Observable.of(response); - - for (let i = startOn; i >= 0; i--) { - let af: Interceptor = this.interceptors[i]; - if (!af.interceptAfter) continue; - - ret = ret.flatMap((value: InterceptedResponse, index) => { - let newObs: Observable; - - let res = null; - try { - res = af.interceptAfter(value); - } catch (ex) { - console.error(ex); - } - if (!res) newObs = Observable.of(value); - else if (!(res instanceof Observable)) newObs = Observable.of(res); - else newObs = res; - - return newObs; - }); - } - return ret; - } + + private interceptors: Array; + private _realResponseObservableTransformer: RealResponseObservableTransformer; + + constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) { + super(backend, defaultOptions); + this.interceptors = []; + } + + /** Parent overrides **/ + request(url: string | Request, options?: RequestOptionsArgs | InterceptorRequestOptionsArgs): Observable { + let interceptorOptions: InterceptorRequestOptionsArgs; + if (options) { + interceptorOptions = {}; + } else if (this.representsInterceptorFlavor(options)) { + interceptorOptions = options; + } else { + interceptorOptions = InterceptorUtils.from(options); + } + interceptorOptions.headers = interceptorOptions.headers || new Headers(); + + const requestWrapper = InterceptorService._InterceptorRequestWrapperBuilder.new() + .url(url) + .options(interceptorOptions) + .sharedData(interceptorOptions.sharedData || {}) + .build(); + return this.httpRequest(requestWrapper); + } + + /** + * Performs a request with `get` http method. + */ + get(url: string, options?: RequestOptionsArgs | InterceptorRequestOptionsArgs): Observable { + options = options || {}; + options.method = RequestMethod.Get; + options.url = options.url || url; + return this.request(url, options); + } + + /** + * Performs a request with `post` http method. + */ + post(url: string, body: any, options?: RequestOptionsArgs | InterceptorRequestOptionsArgs): Observable { + options = options || {}; + options.method = RequestMethod.Post; + options.url = options.url || url; + options.body = options.body || body; + return this.request(url, options); + } + + /** + * Performs a request with `put` http method. + */ + put(url: string, body: any, options?: RequestOptionsArgs | InterceptorRequestOptionsArgs): Observable { + options = options || {}; + options.method = RequestMethod.Put; + options.url = options.url || url; + options.body = options.body || body; + return this.request(url, options); + } + + /** + * Performs a request with `delete` http method. + */ + delete(url: string, options?: RequestOptionsArgs | InterceptorRequestOptionsArgs): Observable { + options = options || {}; + options.method = RequestMethod.Delete; + options.url = options.url || url; + return this.request(url, options); + } + + /** + * Performs a request with `patch` http method. + */ + patch(url: string, body: any, options?: RequestOptionsArgs | InterceptorRequestOptionsArgs): Observable { + options = options || {}; + options.method = RequestMethod.Patch; + options.url = options.url || url; + options.body = options.body || body; + return this.request(url, options); + } + + /** + * Performs a request with `head` http method. + */ + head(url: string, options?: RequestOptionsArgs | InterceptorRequestOptionsArgs): Observable { + options = options || {}; + options.method = RequestMethod.Head; + options.url = options.url || url; + return this.request(url, options); + } + + /** + * Performs a request with `options` http method. + */ + options(url: string, options?: RequestOptionsArgs | InterceptorRequestOptionsArgs): Observable { + options = options || {}; + options.method = RequestMethod.Options; + options.url = options.url || url; + return this.request(url, options); + } + + /** + * Adds this interceptor + */ + addInterceptor(interceptor: Interceptor) { + this.interceptors.push(interceptor); + } + + set realResponseObservableTransformer(value: RealResponseObservableTransformer) { + this._realResponseObservableTransformer = value; + } + + /** Private functions **/ + private httpRequest(requestWrapper: InterceptorRequestWrapper): Observable { + return this.runBeforeInterceptors(requestWrapper) + .flatMap((requestWrapper: InterceptorRequestWrapper, _: number) => { + let interceptedRequestInternal = new InterceptorService._InterceptorRequestWrapper(requestWrapper); + + if (interceptedRequestInternal.err || interceptedRequestInternal.alreadyShortCircuited) { + return Observable.of(requestWrapper); + } else if (interceptedRequestInternal.shortCircuitAtCurrentStep) { + if (interceptedRequestInternal.alsoForceRequestCompletion) { + return Observable.empty(); + } else if (!interceptedRequestInternal.alreadyShortCircuited) { + let requestWrapperBuilder = InterceptorService._InterceptorRequestWrapperBuilder.new(requestWrapper) + .shortCircuitAtCurrentStep(false) + .shortCircuitTriggeredBy(this.interceptors.length - 1) // since the last interceptor in the chain asked for short circuiting + .alreadyShortCircuited(true); + return Observable.of(requestWrapperBuilder.build()); + } else { + return Observable.of(requestWrapper); + } + } + + let response$ = super.request(requestWrapper.url, requestWrapper.options); + if (this._realResponseObservableTransformer) { + response$ = this._realResponseObservableTransformer.tranform(response$, requestWrapper); + } + + return response$.map((response: Response) => { + return InterceptorService._InterceptorResponseWrapperBuilder.new(requestWrapper) + .response(response) + .build(); + }).catch(err => { + let responseBuilder = InterceptorService._InterceptorResponseWrapperBuilder.new(requestWrapper) + .err(err) + .errEncounteredAt(this.interceptors.length) + .errEncounteredInRequestCycle(true); + return Observable.of(responseBuilder.build()); + }); + }) + .flatMap((responseWrapper: InterceptorResponseWrapper, index: number) => { + return this.runAfterInterceptors(responseWrapper); + }) + .flatMap((responseWrapper: InterceptorResponseWrapper, index: number) => { + if (!responseWrapper.response) { + if (responseWrapper.err) { + return Observable.throw(responseWrapper.err); + } else if (responseWrapper.isShortCircuited()) { + return Observable.throw(new Error('Short circuit was triggere, but no short circuit handlers generated any resonse')); + } else { + return Observable.throw(new Error('Response is empty')); + } + } + return Observable.of(responseWrapper.response); + }); + } + + private runBeforeInterceptors(params: InterceptorRequestWrapper): Observable { + let requestWrapper$: Observable = Observable.of(params); + + for (let i: number = 0; i < this.interceptors.length; i++) { + let bf: Interceptor = this.interceptors[i]; + if (!bf.beforeRequest) { + continue; + } + + requestWrapper$ = requestWrapper$ + .flatMap((requestWrapper: InterceptorRequestWrapper, index: number) => { + let interceptedRequestInternal = new InterceptorService._InterceptorRequestWrapper(requestWrapper); + + if (interceptedRequestInternal.err || interceptedRequestInternal.alreadyShortCircuited) { + return Observable.of(requestWrapper); + } else if (interceptedRequestInternal.shortCircuitAtCurrentStep) { + if (interceptedRequestInternal.alsoForceRequestCompletion) { + return Observable.empty(); + } else if (!interceptedRequestInternal.alreadyShortCircuited) { + let requestWrapperBuilder = InterceptorService._InterceptorRequestWrapperBuilder.new(requestWrapper) + .shortCircuitAtCurrentStep(false) + .shortCircuitTriggeredBy(this.interceptors.length - 1) // since the last interceptor in the chain asked for short circuiting + .alreadyShortCircuited(true); + return Observable.of(requestWrapperBuilder.build()); + } else { + return Observable.of(requestWrapper); + } + } + + let modifiedRequest = bf.beforeRequest(requestWrapper); + let newInterceptedRequest$: Observable; + + if (!modifiedRequest) { // if no request is returned; just proceed with the original request + newInterceptedRequest$ = Observable.of(requestWrapper); + } else if (modifiedRequest instanceof Observable) { + newInterceptedRequest$ = >modifiedRequest; + } else { + newInterceptedRequest$ = Observable.of(modifiedRequest); + } + return newInterceptedRequest$ + .catch((err: any, caught: Observable) => { + let responseBuilder = InterceptorService._InterceptorRequestWrapperBuilder.new(requestWrapper) + .err(err) + .errEncounteredAt(i); + return Observable.of(responseBuilder.build()); + }); + }); + } + + return requestWrapper$; + } + + private runAfterInterceptors(responseWrapper: InterceptorResponseWrapper): Observable { + let responseWrapper$: Observable = Observable.of(responseWrapper); + + let startFrom: number; + if (responseWrapper.err) { + startFrom = responseWrapper.errEncounteredAt; + } else if (responseWrapper.isShortCircuited()) { + startFrom = responseWrapper.shortCircuitTriggeredBy; + } else { + this.interceptors.length - 1; + } + + for (let index = startFrom; index >= 0; index--) { + let interceptor: Interceptor = this.interceptors[index]; + if (!interceptor.onResponse) { + continue; + } + + let lastResponseWrapper: InterceptorResponseWrapper; + + responseWrapper$ = responseWrapper$.flatMap((responseWrapper: InterceptorResponseWrapper, _: any) => { + lastResponseWrapper = responseWrapper; + if (responseWrapper.forceRequestCompletion) { + return Observable.empty(); + } else if (responseWrapper.forceReturnResponse) { + return Observable.of(responseWrapper); + } + + let processedResponse; + + const invokeErrHandler = responseWrapper.err && !responseWrapper.response; + const invokeShortCircuitHandler = responseWrapper.isShortCircuited() && !responseWrapper.response; + + if (invokeErrHandler) { + processedResponse = interceptor.onErr(responseWrapper); + } else if (invokeShortCircuitHandler) { + processedResponse = interceptor.onShortCircuit(responseWrapper, index); + } else { + processedResponse = interceptor.onResponse(responseWrapper, index); + } + + if (!processedResponse) { + return Observable.of(responseWrapper); + } else if (processedResponse instanceof InterceptorResponseWrapper) { + return Observable.of(processedResponse as InterceptorResponseWrapper); + } else { + return processedResponse as Observable; + } + }).catch((err: any, _: Observable) => { + let responseBuilder = InterceptorService._InterceptorResponseWrapperBuilder.new(lastResponseWrapper) + .response(undefined) + .err(err) + .errEncounteredAt(index) + .errEncounteredInRequestCycle(false); + return Observable.of(responseBuilder.build()); + }); + } + + return responseWrapper$; + } + + /** + * Tests whether the passed in object represents interceptor version/native request options + */ + private representsInterceptorFlavor(options: RequestOptionsArgs | InterceptorRequestOptionsArgs): options is InterceptorRequestOptionsArgs { + return (options).sharedData !== undefined; + } + + /** + * Class that exposes internal variables of InterceptorRequestWrapper for internal use + */ + private static _InterceptorRequestWrapper = class extends InterceptorRequestWrapper { + + constructor(requestWrapper: InterceptorRequestWrapper) { + super(InterceptorRequestWrapperBuilder.new(requestWrapper)); + } + + shortCircuitAtCurrentStep(shortCircuitAtCurrentStep: boolean): boolean { + return this._shortCircuitAtCurrentStep; + } + + alsoForceRequestCompletion(alsoForceRequestCompletion: boolean): boolean { + return this._alsoForceRequestCompletion; + } + + alreadyShortCircuited(alreadyShortCircuited: boolean): boolean { + return this._alreadyShortCircuited; + } + + shortCircuitTriggeredBy(shortCircuitTriggeredBy: number): number { + return this._shortCircuitTriggeredBy; + } + + err(err: any): any { + return this._err; + } + + errEncounteredAt(errEncounteredAt: number): number { + return this._errEncounteredAt; + } + + } + + /** + * Utility builder for creating a new instance of _InterceptorRequestWrapper with additional ability to set internal properties aswell + * Use _InterceptorRequestWrapperBuilder.new() to instantiate the builder + */ + private static _InterceptorRequestWrapperBuilder = class extends InterceptorRequestWrapperBuilder { + + /** + * Use _InterceptorRequestWrapperBuilder.new() to instantiate the builder + */ + protected constructor() { + super(); + } + + static new(requestWrapper?: InterceptorRequestWrapper) { + const builder = new InterceptorService._InterceptorRequestWrapperBuilder(); + InterceptorUtils.assign(builder, requestWrapper); + return builder; + } + + url(url: string | Request) { + super.url(url); + return this; + } + + options(options: RequestOptionsArgs) { + super.options(options); + return this; + } + + sharedData(sharedData: any) { + super.sharedData(sharedData); + return this; + } + + shortCircuitAtCurrentStep(shortCircuitAtCurrentStep: boolean) { + super.shortCircuitAtCurrentStep(shortCircuitAtCurrentStep); + return this; + } + + alsoForceRequestCompletion(alsoForceRequestCompletion: boolean) { + super.alsoForceRequestCompletion(alsoForceRequestCompletion); + return this; + } + + alreadyShortCircuited(alreadyShortCircuited: boolean) { + this._alreadyShortCircuited = alreadyShortCircuited; + return this; + } + + shortCircuitTriggeredBy(shortCircuitTriggeredBy: number) { + this._shortCircuitTriggeredBy = shortCircuitTriggeredBy; + return this; + } + + err(err: any) { + this._err = err; + return this; + } + + errEncounteredAt(errEncounteredAt: number) { + this._errEncounteredAt = errEncounteredAt; + return this; + } + + } + + /** + * Utility builder for creating a new instance of InterceptorResponseWrapper with additional ability to set internal properties aswell + * Use _InterceptorResponseWrapperBuilder.new() to instantiate the builder + */ + private static _InterceptorResponseWrapperBuilder = class extends InterceptorResponseWrapperBuilder { + + /** + * Use _InterceptorResponseWrapperBuilder.new() to instantiate the builder + */ + protected constructor() { + super(); + } + + static new(from?: Response | InterceptorResponseWrapper | InterceptorRequestWrapper) { + const builder = new InterceptorService._InterceptorResponseWrapperBuilder(); + if (from instanceof Response) { + builder._response = from; + } else if (from instanceof InterceptorResponseWrapper) { + InterceptorUtils.assign(builder, from); + } else { + InterceptorUtils.assign(builder, from); + } + return builder; + } + + url(url: string | Request) { + this._url = url; + return this; + } + + options(options: RequestOptionsArgs | InterceptorRequestOptionsArgs) { + this._options = options; + return this; + } + + response(response: Response) { + super.response(response); + return this; + } + + sharedData(sharedData: any) { + super.sharedData(sharedData); + return this; + } + + shortCircuitTriggeredBy(shortCircuitTriggeredBy: number) { + this._shortCircuitTriggeredBy = shortCircuitTriggeredBy; + return this; + } + + forceReturnResponse(forceReturnResponse: boolean) { + super.forceReturnResponse(forceReturnResponse); + return this; + } + + forceRequestCompletion(forceRequestCompletion: boolean) { + super.forceRequestCompletion(forceRequestCompletion); + return this; + } + + responseGeneratedByShortCircuitHandler(responseGeneratedByShortCircuitHandler: boolean) { + this._responseGeneratedByShortCircuitHandler = responseGeneratedByShortCircuitHandler; + return this; + } + + err(err: any) { + super.err(err); + return this; + } + + errEncounteredAt(errEncounteredAt: number) { + this._errEncounteredAt = errEncounteredAt; + return this; + } + + errEncounteredInRequestCycle(errEncounteredInRequestCycle: boolean) { + this._errEncounteredInRequestCycle = errEncounteredInRequestCycle; + return this; + } + + } + } diff --git a/src/interceptor-utils.ts b/src/interceptor-utils.ts new file mode 100644 index 0000000..699c055 --- /dev/null +++ b/src/interceptor-utils.ts @@ -0,0 +1,30 @@ +import { RequestOptionsArgs } from '@angular/http/src/interfaces'; +import { InterceptorRequestOptionsArgs } from './interceptor-request-options-args'; + +export class InterceptorUtils { + /** + * Forcing the user to use static methods, as this is a utility class + */ + private constructor() { + } + + static from(options: RequestOptionsArgs): InterceptorRequestOptionsArgs { + const interceptorRequestOptionsArgs: InterceptorRequestOptionsArgs = {}; + InterceptorUtils.assign(interceptorRequestOptionsArgs, options); + interceptorRequestOptionsArgs.sharedData = {}; + return interceptorRequestOptionsArgs; + } + + static assign(target: any, ...args: any[]) { + if (!target) { + throw TypeError('Cannot convert undefined or null to object'); + } + for (const source of args) { + if (source) { + Object.keys(source).forEach(key => target[key] = source[key]); + } + } + return target; + } + +} diff --git a/src/interceptor.ts b/src/interceptor.ts index 0b3953e..4d6e35c 100644 --- a/src/interceptor.ts +++ b/src/interceptor.ts @@ -1,8 +1,61 @@ -import { InterceptedRequest } from "./intercepted-request"; -import { InterceptedResponse } from "./intercepted-response"; import { Observable } from 'rxjs/Rx'; +import { InterceptorRequestWrapper } from "./interceptor-request-wrapper"; +import { InterceptorResponseWrapper } from "./interceptor-response-wrapper"; + +/** + * Represents an intermediary in the interceptor chain that intercept both HTTP request & response flow + * + * Implementors will have the ability to + * 1. Modify the request the along the chain/perform operations such as logging/caching/tranformations; such as adding a header + * 2. Modify the response along the chain + * 3. Intercept errors; Can chose to cascade/generate responses + * 4. Short circuit complete request flow dynamically based on the dynamic conditions without affecting the actual controller/service + * 5. Ability to perform custom logic; such as redirecting the users to login page, if the server returns 401, transparantly without polluting all your services + * + * NOTE: Never store any data that's request specific as properties on the Interceptor implementation, as the interceptor instance is shared across all http requests within the application. Instead use `InterceptorRequestOptionsArgs.sharedData` (or) `InterceptorRequestWrapper.sharedData` (or) `InterceptorResponseWrapper.sharedData` as request private storage + */ export interface Interceptor { - interceptBefore?(request: InterceptedRequest): Observable | InterceptedRequest - interceptAfter?(response: InterceptedResponse): Observable | InterceptedResponse + + /** + * Invoked once for each of the interceptors in the chain; in the order defined in the chain, unless any of the earlier interceptors asked to complete the flow/return response/throw error to subscriber + * + * Gives the ability to transform the request + */ + beforeRequest?(request: InterceptorRequestWrapper, interceptorStep?: number): Observable | InterceptorRequestWrapper | void; + + /** + * Invoked once for each of the interceptors in the chain; in the reverse order of chain, unless any of the earlier interceptors asked to complete the flow/return response/throw error to subscriber + * + * Gives the ability to transform the response in each of the following scenarios + * 1. For normal response flow; i.e no errors along the chain/no interceptor wanted to short the circuit + * 2. One of the interceptor indicated to short the circuit & one of the earlier interceptor in chain returned a InterceptorResponseWrapper when its onShortCircuit(..) method is invoked + * 3. One of the interceptor threw error & one of the earlier interceptor in chain returned a `InterceptorResponseWrapper` when its onErr(..) method is invoked + * + * Set any of the following properties of `InterceptorResponseWrapper` to be able to change the way response to sent to subscriber + * a. `forceReturnResponse` - will send the `Response` to the subscriber directly by skipping all intermediate steps + * b. `forceRequestCompletion` - will send completion event, so that complete(..) will be invoked on the subscriber + * + * You can know if the respons is generated by short circuit handler/err handler, by looking at the `responseGeneratedByShortCircuitHandler` & `responseGeneratedByErrHandler` flags + */ + onResponse?(response: InterceptorResponseWrapper, interceptorStep?: number): Observable | InterceptorResponseWrapper | void; + + /** + * Invoked once for each of the interceptors in the chain; in the reverse order of chain, if any of the `beforeRequest(..)` responded by setting `shortCircuitAtCurrentStep` property of `InterceptorRequestWrapper` + * Use this method to generate a response that gets sent to the subscriber. + * If you return nothing, the `onShortCircuit(..) will be cascaded along the interceptor chain + * If you return an Observable | InterceptorResponseWrapper, this rest of the flow would be continued on `onResponse(..)` instead of `onErr(..)` on the next interceptor in the chain & the final result would be sent to the subscriber via next(..) callback + * If no `onShortCircuit(..)` handlers before this handler returns any response, an error will be thrown back to the subscriber + */ + onShortCircuit?(response: InterceptorResponseWrapper, interceptorStep?: number): Observable | InterceptorResponseWrapper | void; + + /** + * Invoked when the flow encounters any error along the interceptor chain. + * Use this method to generate a response that gets sent to the subscriber. + * If you return nothing, the `onErr(..) will be cascaded along the interceptor chain + * If you return an Observable | InterceptorResponseWrapper, this rest of the flow would be continued on `onResponse(..)` instead of `onErr(..)` on the next interceptor in the chain & the final result would be sent to the subscriber via next(..) callback + * If no `onErr(..)` handlers before this handler returns any response, the error will be thrown back to the subscriber + */ + onErr?(err: any): Observable | InterceptorResponseWrapper | void; + } diff --git a/src/real-response-observable-transformer.ts b/src/real-response-observable-transformer.ts new file mode 100644 index 0000000..2632c01 --- /dev/null +++ b/src/real-response-observable-transformer.ts @@ -0,0 +1,14 @@ +import { Observable } from 'rxjs/Rx'; +import { Response } from '@angular/http'; +import { InterceptorRequestWrapper } from './interceptor-request-wrapper'; + +/** + * Gives access to the `Observable` returned by tha angular `Http` api. + * Can be used augment the real observable + * Sample Use cases: + * 1. OAuth2 requires request to be retried with new access token if existing token is expired + * 2. Allows user to retry the request if the requets is expired due to connection timeout using `Observable.retry`/`Observable.retryWhen` + */ +export interface RealResponseObservableTransformer { + tranform(response: Observable, request: InterceptorRequestWrapper): Observable; +} diff --git a/src/tsconfig.json b/src/tsconfig.json index bcb923a..d21a10e 100644 --- a/src/tsconfig.json +++ b/src/tsconfig.json @@ -1,17 +1,15 @@ { "compilerOptions": { - "target": "es5", - "module": "commonjs", - "moduleResolution": "node", - "sourceMap": true, + "declaration": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, - "removeComments": false, + "lib": ["es6", "dom"], + "module": "es6", + "moduleResolution": "node", "noImplicitAny": false, "outDir": "../lib", - "declaration": true - }, - "exclude": [ - "node_modules" - ] + "removeComments": false, + "sourceMap": true, + "target": "es5" + } } diff --git a/yarn.lock b/yarn.lock index ddc44dc..bbbd149 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,25 +2,25 @@ # yarn lockfile v1 -"@angular/common@^2.0.0": - version "2.3.0" - resolved "https://registry.yarnpkg.com/@angular/common/-/common-2.3.0.tgz#16b0034fe43ae70875343f23e19835435edd118e" +"@angular/common@>=4.0.0-beta.1 <5": + version "4.0.0-beta.3" + resolved "https://registry.yarnpkg.com/@angular/common/-/common-4.0.0-beta.3.tgz#da6679ae716dbf934098f3393f45db148eeb1d0b" -"@angular/core@^2.0.0": - version "2.3.0" - resolved "https://registry.yarnpkg.com/@angular/core/-/core-2.3.0.tgz#e60bd398584d69467d075d001b718364174a2534" +"@angular/core@>=4.0.0-beta.1 <5": + version "4.0.0-beta.3" + resolved "https://registry.yarnpkg.com/@angular/core/-/core-4.0.0-beta.3.tgz#17a09d0fa631edd9c7767ad567bd16aab21898e0" -"@angular/http@^2.0.0": - version "2.3.0" - resolved "https://registry.yarnpkg.com/@angular/http/-/http-2.3.0.tgz#0c0823d69723d96d294e58881397fec1ed803f73" +"@angular/http@>=4.0.0-beta.1 <5": + version "4.0.0-beta.3" + resolved "https://registry.yarnpkg.com/@angular/http/-/http-4.0.0-beta.3.tgz#0cbc22d164d95d50e408bd14ef0daccaa0801eb2" -"@angular/platform-browser@^2.0.0": - version "2.3.0" - resolved "https://registry.yarnpkg.com/@angular/platform-browser/-/platform-browser-2.3.0.tgz#93259309cfb4e8fdb39ececa0b205f4caf002e6c" +"@angular/platform-browser@>=4.0.0-beta.1 <5": + version "4.0.0-beta.3" + resolved "https://registry.yarnpkg.com/@angular/platform-browser/-/platform-browser-4.0.0-beta.3.tgz#fe68e19a7745c20a8721040f4ea8e17e5289bc02" -rxjs@^5.0.0-beta.12: - version "5.0.1" - resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-5.0.1.tgz#3a69bdf9f0ca0a986303370d4708f72bdfac8356" +rxjs@^5.0.0: + version "5.0.3" + resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-5.0.3.tgz#fc8bdf464ebf938812748e4196788f392fef9754" dependencies: symbol-observable "^1.0.1" @@ -29,8 +29,8 @@ symbol-observable@^1.0.1: resolved "https://registry.yarnpkg.com/symbol-observable/-/symbol-observable-1.0.4.tgz#29bf615d4aa7121bdd898b22d4b3f9bc4e2aa03d" typescript@^2.0.3: - version "2.1.4" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.1.4.tgz#b53b69fb841126acb1dd4b397d21daba87572251" + version "2.1.5" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.1.5.tgz#6fe9479e00e01855247cea216e7561bafcdbcd4a" zone.js@^0.6.21: version "0.6.26" From 2bdb06a3c08869548ad60eee79d74ec8c26b40a9 Mon Sep 17 00:00:00 2001 From: Ashok Koyi Date: Thu, 19 Jan 2017 15:33:12 +0530 Subject: [PATCH 2/8] Changed README & performed lil bit of code cleaup --- .npmignore | 7 +- .vscode/settings.json | 8 + README.md | 199 +++++++++++------- index.d.ts | 15 +- index.js | 11 +- src/interceptor-provider.ts | 47 ----- ...lder.ts => interceptor-request-builder.ts} | 30 +-- ...uest-wrapper.ts => interceptor-request.ts} | 6 +- src/interceptor-service.ts | 112 +++++----- src/interceptor.ts | 8 +- src/real-response-observable-transformer.ts | 4 +- 11 files changed, 236 insertions(+), 211 deletions(-) create mode 100644 .vscode/settings.json delete mode 100644 src/interceptor-provider.ts rename src/{interceptor-request-wrapper-builder.ts => interceptor-request-builder.ts} (60%) rename src/{interceptor-request-wrapper.ts => interceptor-request.ts} (93%) diff --git a/.npmignore b/.npmignore index bf40d27..d268676 100644 --- a/.npmignore +++ b/.npmignore @@ -1,2 +1,7 @@ +.vscode node_modules -src \ No newline at end of file +src +.editorconfig +.gitignore +README.md +yarn.lock diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..4e42b49 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,8 @@ +// Place your settings in this file to overwrite default and user settings. +{ + "search.exclude": { + "**/node_modules": true, + "**/bower_components": true, + "**/lib": true + } +} diff --git a/README.md b/README.md index b753ca9..204ef49 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ -# NG2-Interceptors +# ng-http-interceptor -This package adds the interceptor feature to Angular 2, by extending the @angular/http class. For concept behind Interceptor, take a look at the [wiki](https://github.com/voliva/angular2-interceptors/wiki/Concept) +This package adds the intercepting capabilities to `http` module of Angular 2+, by extending the @angular/http class. For concept behind Interceptor, take a look at the [wiki](https://github.com/voliva/angular2-interceptors/wiki/Concept) # Installation To install, just run in your angular project: -```` -npm install ng2-interceptors --save -```` +``` +npm install ng-http-interceptor --save +``` And it should be importable with webpack out of the box @@ -16,11 +16,12 @@ And it should be importable with webpack out of the box ## Set up InterceptorService Interceptors are registered when the service is created (to avoid any race-condition). To do so, you have to provide the instance of the service by yourself. So on your module declaration, you should put a provider like: -```` -import { InterceptorService } from 'ng2-interceptors'; +```ts import { XHRBackend, RequestOptions } from '@angular/http'; -export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions){ +import { InterceptorService } from 'ng-http-interceptor'; + +export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions) { let service = new InterceptorService(xhrBackend, requestOptions); // Add interceptors here with service.addInterceptor(interceptor) return service; @@ -43,35 +44,13 @@ export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: Reque ], bootstrap: [AppComponent] }) -```` - -There's a shorthand for this setup by using `provideInterceptorService`, but if you use AoT (Ahead-of-time) compilation it will fail. In fact, exporting the `interceptorFactory` is to make the AoT Compiler, as it needs all functions used in the provider to be exported. - -```` -import { provideInterceptorService } from 'ng2-interceptors'; - -@NgModule({ - declarations: [ - ... - ], - imports: [ - ..., - HttpModule - ], - providers: [ - provideInterceptorService([ - // Add interceptors here, like "new ServerURLInterceptor()" or just "ServerURLInterceptor" if it has a provider - ]) - ], - bootstrap: [AppComponent] -}) -```` +``` ## Using InterceptorService Once we have it set up, we can use it in our Controllers as if we were using the default Angular `Http` service: -```` +```ts import { Component } from '@angular/core'; -import { InterceptorService } from 'ng2-interceptors'; +import { InterceptorService } from 'ng-http-interceptor'; @Component({ selector: 'my-component', @@ -91,65 +70,135 @@ export class MyComponent { () => console.log("Yay")); } } -```` +``` We can also "cheat" the Injector so that every time we ask for the `Http` we get the `InterceptorService` instead. All we have to do is replace `InterceptorService` on the provider definition for `Http`, and then we can get our service when we use `private http: Http`: -```` - { - provide: Http, - useFactory: interceptorFactory, - deps: [XHRBackend, RequestOptions] - } -```` +```ts +{ + provide: Http, + useFactory: interceptorFactory, + deps: [XHRBackend, RequestOptions] +} +``` ## Creating your own Interceptor -Basically, an interceptor is represented by one pair of functions: One that will get the request that's about to be sent to the server, and another that will get the response that the server just sent. For that, we just need to create a new class that implements Interceptor: +Basically, an interceptor has the option to selectively implement one more of the following methods depending on what part of the flow it wants to intercept. i.e modify flow/take action. + +Here is the interceptor interface that details which method is invoked in what part of the flow + +```ts +/** + * Represents an intermediary in the interceptor chain that intercept both HTTP request & response flow + * + * Implementors will have the ability to + * 1. Modify the request the along the chain/perform operations such as logging/caching/tranformations; such as adding a header + * 2. Modify the response along the chain + * 3. Intercept errors; Can chose to cascade/generate responses + * 4. Short circuit complete request flow dynamically based on the dynamic conditions without affecting the actual controller/service + * 5. Ability to perform custom logic; such as redirecting the users to login page, if the server returns 401, transparantly without polluting all your services + * + * NOTE: Never store any data that's request specific as properties on the Interceptor implementation, as the interceptor instance is shared across all http requests within the application. Instead use `InterceptorRequestOptionsArgs.sharedData` (or) `InterceptorRequest.sharedData` (or) `InterceptorResponseWrapper.sharedData` as request private storage + */ +export interface Interceptor { + + /** + * Invoked once for each of the interceptors in the chain; in the order defined in the chain, unless any of the earlier interceptors asked to complete the flow/return response/throw error to subscriber + * + * Gives the ability to transform the request + */ + beforeRequest?(request: InterceptorRequest, interceptorStep?: number): Observable | InterceptorRequest | void; + + /** + * Invoked once for each of the interceptors in the chain; in the reverse order of chain, unless any of the earlier interceptors asked to complete the flow/return response/throw error to subscriber + * + * Gives the ability to transform the response in each of the following scenarios + * 1. For normal response flow; i.e no errors along the chain/no interceptor wanted to short the circuit + * 2. One of the interceptor indicated to short the circuit & one of the earlier interceptor in chain returned a InterceptorResponseWrapper when its onShortCircuit(..) method is invoked + * 3. One of the interceptor threw error & one of the earlier interceptor in chain returned a `InterceptorResponseWrapper` when its onErr(..) method is invoked + * + * Set any of the following properties of `InterceptorResponseWrapper` to be able to change the way response to sent to subscriber + * a. `forceReturnResponse` - will send the `Response` to the subscriber directly by skipping all intermediate steps + * b. `forceRequestCompletion` - will send completion event, so that complete(..) will be invoked on the subscriber + * + * You can know if the respons is generated by short circuit handler/err handler, by looking at the `responseGeneratedByShortCircuitHandler` & `responseGeneratedByErrHandler` flags + */ + onResponse?(response: InterceptorResponseWrapper, interceptorStep?: number): Observable | InterceptorResponseWrapper | void; + + /** + * Invoked once for each of the interceptors in the chain; in the reverse order of chain, if any of the `beforeRequest(..)` responded by setting `shortCircuitAtCurrentStep` property of `InterceptorRequest` + * Use this method to generate a response that gets sent to the subscriber. + * If you return nothing, the `onShortCircuit(..) will be cascaded along the interceptor chain + * If you return an Observable | InterceptorResponseWrapper, this rest of the flow would be continued on `onResponse(..)` instead of `onErr(..)` on the next interceptor in the chain & the final result would be sent to the subscriber via next(..) callback + * If no `onShortCircuit(..)` handlers before this handler returns any response, an error will be thrown back to the subscriber + */ + onShortCircuit?(response: InterceptorResponseWrapper, interceptorStep?: number): Observable | InterceptorResponseWrapper | void; + + /** + * Invoked when the flow encounters any error along the interceptor chain. + * Use this method to generate a response that gets sent to the subscriber. + * If you return nothing, the `onErr(..) will be cascaded along the interceptor chain + * If you return an Observable | InterceptorResponseWrapper, this rest of the flow would be continued on `onResponse(..)` instead of `onErr(..)` on the next interceptor in the chain & the final result would be sent to the subscriber via next(..) callback + * If no `onErr(..)` handlers before this handler returns any response, the error will be thrown back to the subscriber + */ + onErr?(err: any): Observable | InterceptorResponseWrapper | void; + +} +``` -```` -import { Interceptor, InterceptedRequest, InterceptedResponse } from 'ng2-interceptors'; +One that will get the request that's about to be sent to the server, and another that will get the response that the server just sent. For that, we just need to create a new class that implements Interceptor: + +```ts +import { Interceptor, InterceptorRequest, InterceptorResponseWrapper } from 'ng-http-interceptor'; export class ServerURLInterceptor implements Interceptor { - public interceptBefore(request: InterceptedRequest): InterceptedRequest { - // Do whatever with request: get info or edit it - - return request; - /* - You can return: - - Request: The modified request - - Nothing: For convenience: It's just like returning the request - - (Observable.throw("cancelled")): Cancels the request, interrupting it from the pipeline, and calling back 'interceptAfter' in backwards order of those interceptors that got called up to this point. - */ + beforeRequest(request: InterceptorRequest): Observable | InterceptorRequest | void { + // Do whatever with request, such as chaing request by adding additional headers such as `Content-Type` (or) `Authorization` + // refer to jsdoc of each of 'InterceptorRequest' to know the significance of return values & additional features such as short circuiting the whole flow + let modifiedOptions: RequestOptionsArgs = addHeaders(request.options); + return InterceptorRequestBuilder.from(request) + .options(modifiedOptions) + .build(); } - public interceptAfter(response: InterceptedResponse): InterceptedResponse { - // Do whatever with response: get info or edit it + onResponse(responseWrapper: InterceptorResponseWrapper, interceptorStep?: number): Observable | InterceptorResponseWrapper | void { + // Do whatever with responseWrapper: get/edit response + // refer to jsdoc of each of 'InterceptorResponseWrapper' to know the significance of return values & additional features such as short circuiting the whole flow - return response; - /* - You can return: - - Response: The modified response - - Nothing: For convenience: It's just like returning the response - */ + return InterceptorResponseWrapperBuilder.from(responseWrapper) + .forceReturnResponse(true) + .build(); } + + // can chose to seletively implement any of the four hooks mentioned in the Interceptor interface } -```` +``` + +All four methods are optional, so you can implement the callback method depending on whether you want to augment the request/response/handling exceptions/handling short circuits -Both methods are optional, so you can implement Interceptors that just take request or responses. +Notice how there's a different object of `InterceptorRequest` and `InterceptedResponseWrapper`. -Notice how there's a different object of `InterceptedRequest` and `InterceptedResponse`: They are modifications of angular's Http `Request` and `Response` needed for the whole Interceptor feature and to pass additional options that may be needed for specific interceptors (like to enable/disable them for specific calls, etc.) the API is: +`InterceptorRequest` is a modification of angular's Http `Request` & `InterceptedResponseWrapper.response` is angular's Http `Response`. -```` -interface InterceptedRequest { +Use `sharedData` to share data across the interceptors for this request. Each http request flow will have its own instance of shared data. +One usecase for this `sharedData` is to store a flag to enable caching for a specific requests, which the cahching interceptor will adhere to. + +the API is: + +```ts +class InterceptorRequest { url: string, options?: RequestOptionsArgs, // Angular's HTTP Request options - interceptorOptions?: any + sharedData?: any, + // a lot more properties; refer to jsdoc } -interface InterceptedResponse { + +class InterceptedResponseWrapper { response: Response, // Angular's HTTP Response - interceptorOptions?: any + sharedData?: any, + // a lot more properties; refer to jsdoc } -```` -`interceptorOptions` on `InterceptedRequest` is guaranteed to be the same of that one of `InterceptedResponse` for the same call: The stuff you put in `interceptorOptions` while in `interceptBefore` will be available when you get `interceptAfter` called. +``` +`sharedData` on `InterceptorRequest` is guaranteed to be the same of that one of `InterceptedResponseWrapper` for the same call: The stuff you put in `interceptorOptions` while in `interceptBefore` will be available when you get `onResponse(..)` called. ## Creating one Injectable Interceptor Interceptors are usually pure classes with pure functions: Given a call, they return a modified one, but sometimes we need these Interceptors to be actual Services to be used all around our application. @@ -166,8 +215,8 @@ To do that you have to do some steps in the module/factory declaration file: If you are using the `provideInterceptorService` option (without AoT Compiler support), then you can skip steps 2-4. If our `ServerURLInterceptor` were a Service, we would have a module declaration like: -```` -import { InterceptorService } from 'ng2-interceptors'; +```ts +import { InterceptorService } from 'ng-http-interceptor'; import { ServerURLInterceptor } from './services/serverURLInterceptor'; import { XHRBackend, RequestOptions } from '@angular/http'; @@ -195,4 +244,4 @@ export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: Reque ], bootstrap: [AppComponent] }) -```` +``` diff --git a/index.d.ts b/index.d.ts index 34fb76f..ab41efd 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,6 +1,9 @@ -// export { InterceptedRequest } from "./lib/intercepted-request"; -// export { InterceptedResponse } from "./lib/intercepted-response"; -// export { InterceptorOptions } from "./lib/interceptor-options"; -// export { InterceptorService } from "./lib/interceptor-service"; -// export { provideInterceptorService } from "./lib/interceptor-provider"; -// export { Interceptor } from "./lib/interceptor"; +export { InterceptorRequestBuilder } from "./lib/interceptor-request-builder"; +export { InterceptorRequestOptionsArgs } from "./lib/interceptor-request-options-args"; +export { InterceptorRequest } from "./lib/interceptor-request"; +export { InterceptorResponseWrapperBuilder } from "./lib/interceptor-response-wrapper-builder"; +export { InterceptorResponseWrapper } from "./lib/interceptor-response-wrapper"; +export { InterceptorService } from "./lib/interceptor-service"; +export { InterceptorUtils } from "./lib/interceptor-utils"; +export { Interceptor } from "./lib/interceptor"; +export { RealResponseObservableTransformer } from './lib/real-response-observable-transformer'; diff --git a/index.js b/index.js index 95914af..426b40e 100644 --- a/index.js +++ b/index.js @@ -1,2 +1,9 @@ -// exports.InterceptorService = require('./lib/interceptor-service').InterceptorService; -// exports.provideInterceptorService = require('./lib/interceptor-provider').provideInterceptorService; +exports.InterceptorRequestBuilder = require('./lib/interceptor-request-builder').InterceptorRequestBuilder; +exports.InterceptorRequestOptionsArgs = require('./lib/interceptor-request-options-args').InterceptorRequestOptionsArgs; +exports.InterceptorRequest = require('./lib/interceptor-request').InterceptorRequest; +exports.InterceptorResponseWrapperBuilder = require('./lib/interceptor-response-wrapper-builder').InterceptorResponseWrapperBuilder; +exports.InterceptorResponseWrapper = require('./lib/interceptor-response-wrapper').InterceptorResponseWrapper; +exports.InterceptorService = require('./lib/interceptor-service').InterceptorService; +exports.InterceptorUtils = require('./lib/interceptor-utils').InterceptorUtils; +exports.Interceptor = require('./lib/interceptor').Interceptor; +exports.RealResponseObservableTransformer = require('./lib/real-response-observable-transformer').RealResponseObservableTransformer; diff --git a/src/interceptor-provider.ts b/src/interceptor-provider.ts deleted file mode 100644 index f772293..0000000 --- a/src/interceptor-provider.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { FactoryProvider } from '@angular/core'; -import { XHRBackend, RequestOptions } from '@angular/http'; - -import { InterceptorService } from './interceptor-service'; - -export function provideInterceptorService(interceptors: any[]): FactoryProvider { - let deps: any[] = [ - XHRBackend, - RequestOptions - ]; - - interceptors = interceptors.map((interceptor: any) => { - if (typeof interceptor == "function") { - deps.push(interceptor); - return { - useValue: false, - index: deps.length - 1 - } - } else { - return { - useValue: interceptor - } - } - }); - - return { - provide: InterceptorService, - useFactory: function () { - let injectedServices = arguments; - let xhrBackend: XHRBackend = injectedServices[0]; - let requestOptions: RequestOptions = injectedServices[1]; - - let service = new InterceptorService(xhrBackend, requestOptions); - interceptors.forEach((interceptor) => { - if (interceptor.useValue) { - service.addInterceptor(interceptor.useValue); - } else { - let value = injectedServices[interceptor.index]; - service.addInterceptor(value); - } - }); - return service; - }, - deps: deps, - multi: false - } -} diff --git a/src/interceptor-request-wrapper-builder.ts b/src/interceptor-request-builder.ts similarity index 60% rename from src/interceptor-request-wrapper-builder.ts rename to src/interceptor-request-builder.ts index d0a6dc2..74c1a74 100644 --- a/src/interceptor-request-wrapper-builder.ts +++ b/src/interceptor-request-builder.ts @@ -3,14 +3,14 @@ import { resolveReflectiveProviders } from '@angular/core/src/di/reflective_prov import { reflector } from '@angular/platform-browser/src/private_import_core'; import { Request, Response } from '@angular/http'; -import { InterceptorRequestWrapper } from "./interceptor-request-wrapper"; +import { InterceptorRequest } from "./interceptor-request"; import { InterceptorUtils } from './interceptor-utils'; /** - * Utility builder for creating a new instance of InterceptorRequestWrapper - * Use InterceptorRequestWrapperBuilder.new() to instantiate the builder + * Utility builder for creating a new instance of InterceptorRequest + * Use InterceptorRequestBuilder.new() to instantiate the builder */ -export class InterceptorRequestWrapperBuilder { +export class InterceptorRequestBuilder { protected _url: string | Request; protected _options?: RequestOptionsArgs; @@ -23,44 +23,44 @@ export class InterceptorRequestWrapperBuilder { protected _errEncounteredAt?: number; /** - * Use InterceptorResponseBuilder.new() to instantiate the builder + * Use InterceptorRequestBuilder.new() to instantiate the builder */ protected constructor() { } - static new(requestWrapper: InterceptorRequestWrapper): InterceptorRequestWrapperBuilder { - const builder = new InterceptorRequestWrapperBuilder(); - InterceptorUtils.assign(builder, requestWrapper); + static new(request: InterceptorRequest): InterceptorRequestBuilder { + const builder = new InterceptorRequestBuilder(); + InterceptorUtils.assign(builder, request); return builder; } - url(url: string | Request): InterceptorRequestWrapperBuilder { + url(url: string | Request): InterceptorRequestBuilder { this._url = url; return this; } - options(options: RequestOptionsArgs): InterceptorRequestWrapperBuilder { + options(options: RequestOptionsArgs): InterceptorRequestBuilder { this._options = options; return this; } - sharedData(sharedData: any): InterceptorRequestWrapperBuilder { + sharedData(sharedData: any): InterceptorRequestBuilder { this._sharedData = sharedData; return this; } - shortCircuitAtCurrentStep(shortCircuitAtCurrentStep: boolean): InterceptorRequestWrapperBuilder { + shortCircuitAtCurrentStep(shortCircuitAtCurrentStep: boolean): InterceptorRequestBuilder { this._shortCircuitAtCurrentStep = shortCircuitAtCurrentStep; return this; } - alsoForceRequestCompletion(alsoForceRequestCompletion: boolean): InterceptorRequestWrapperBuilder { + alsoForceRequestCompletion(alsoForceRequestCompletion: boolean): InterceptorRequestBuilder { this._alsoForceRequestCompletion = alsoForceRequestCompletion; return this; } - build(): InterceptorRequestWrapper { + build(): InterceptorRequest { this._sharedData = this._sharedData || {}; - return new InterceptorRequestWrapper(this); + return new InterceptorRequest(this); } } diff --git a/src/interceptor-request-wrapper.ts b/src/interceptor-request.ts similarity index 93% rename from src/interceptor-request-wrapper.ts rename to src/interceptor-request.ts index 9269281..d6ebc54 100644 --- a/src/interceptor-request-wrapper.ts +++ b/src/interceptor-request.ts @@ -1,11 +1,11 @@ import { Request, RequestOptionsArgs } from '@angular/http'; -import { InterceptorRequestWrapperBuilder } from './interceptor-request-wrapper-builder'; +import { InterceptorRequestBuilder } from './interceptor-request-builder'; import { InterceptorUtils } from './interceptor-utils'; -export class InterceptorRequestWrapper { +export class InterceptorRequest { - constructor(builder: InterceptorRequestWrapperBuilder) { + constructor(builder: InterceptorRequestBuilder) { InterceptorUtils.assign(this, builder); } diff --git a/src/interceptor-service.ts b/src/interceptor-service.ts index 69b1424..caa2a60 100644 --- a/src/interceptor-service.ts +++ b/src/interceptor-service.ts @@ -13,11 +13,11 @@ import { RequestOptionsArgs } from '@angular/http/src/interfaces'; import { Observable, Observer } from 'rxjs/Rx'; import { ErrorObservable } from 'rxjs/observable/ErrorObservable'; -import { InterceptorRequestWrapper } from './interceptor-request-wrapper'; +import { InterceptorRequest } from './interceptor-request'; import { InterceptorResponseWrapper } from './interceptor-response-wrapper'; import { Interceptor } from './interceptor'; import { InterceptorRequestOptionsArgs } from './interceptor-request-options-args'; -import { InterceptorRequestWrapperBuilder } from './interceptor-request-wrapper-builder'; +import { InterceptorRequestBuilder } from './interceptor-request-builder'; import { InterceptorResponseWrapperBuilder } from './interceptor-response-wrapper-builder'; import { InterceptorUtils } from './interceptor-utils'; import { RealResponseObservableTransformer } from './real-response-observable-transformer'; @@ -63,12 +63,12 @@ export class InterceptorService extends Http { } interceptorOptions.headers = interceptorOptions.headers || new Headers(); - const requestWrapper = InterceptorService._InterceptorRequestWrapperBuilder.new() + const request = InterceptorService._InterceptorRequestBuilder.new() .url(url) .options(interceptorOptions) .sharedData(interceptorOptions.sharedData || {}) .build(); - return this.httpRequest(requestWrapper); + return this.httpRequest(request); } /** @@ -156,38 +156,38 @@ export class InterceptorService extends Http { } /** Private functions **/ - private httpRequest(requestWrapper: InterceptorRequestWrapper): Observable { - return this.runBeforeInterceptors(requestWrapper) - .flatMap((requestWrapper: InterceptorRequestWrapper, _: number) => { - let interceptedRequestInternal = new InterceptorService._InterceptorRequestWrapper(requestWrapper); - - if (interceptedRequestInternal.err || interceptedRequestInternal.alreadyShortCircuited) { - return Observable.of(requestWrapper); - } else if (interceptedRequestInternal.shortCircuitAtCurrentStep) { - if (interceptedRequestInternal.alsoForceRequestCompletion) { + private httpRequest(request: InterceptorRequest): Observable { + return this.runBeforeInterceptors(request) + .flatMap((request: InterceptorRequest, _: number) => { + let interceptorRequestInternal = new InterceptorService._InterceptorRequestBuilder(request); + + if (interceptorRequestInternal.err || interceptorRequestInternal.alreadyShortCircuited) { + return Observable.of(request); + } else if (interceptorRequestInternal.shortCircuitAtCurrentStep) { + if (interceptorRequestInternal.alsoForceRequestCompletion) { return Observable.empty(); - } else if (!interceptedRequestInternal.alreadyShortCircuited) { - let requestWrapperBuilder = InterceptorService._InterceptorRequestWrapperBuilder.new(requestWrapper) + } else if (!interceptorRequestInternal.alreadyShortCircuited) { + let requestBuilder = InterceptorService._InterceptorRequestBuilder.new(request) .shortCircuitAtCurrentStep(false) .shortCircuitTriggeredBy(this.interceptors.length - 1) // since the last interceptor in the chain asked for short circuiting .alreadyShortCircuited(true); - return Observable.of(requestWrapperBuilder.build()); + return Observable.of(requestBuilder.build()); } else { - return Observable.of(requestWrapper); + return Observable.of(request); } } - let response$ = super.request(requestWrapper.url, requestWrapper.options); + let response$ = super.request(request.url, request.options); if (this._realResponseObservableTransformer) { - response$ = this._realResponseObservableTransformer.tranform(response$, requestWrapper); + response$ = this._realResponseObservableTransformer.tranform(response$, request); } return response$.map((response: Response) => { - return InterceptorService._InterceptorResponseWrapperBuilder.new(requestWrapper) + return InterceptorService._InterceptorResponseWrapperBuilder.new(request) .response(response) .build(); }).catch(err => { - let responseBuilder = InterceptorService._InterceptorResponseWrapperBuilder.new(requestWrapper) + let responseBuilder = InterceptorService._InterceptorResponseWrapperBuilder.new(request) .err(err) .errEncounteredAt(this.interceptors.length) .errEncounteredInRequestCycle(true); @@ -211,8 +211,8 @@ export class InterceptorService extends Http { }); } - private runBeforeInterceptors(params: InterceptorRequestWrapper): Observable { - let requestWrapper$: Observable = Observable.of(params); + private runBeforeInterceptors(params: InterceptorRequest): Observable { + let request$: Observable = Observable.of(params); for (let i: number = 0; i < this.interceptors.length; i++) { let bf: Interceptor = this.interceptors[i]; @@ -220,39 +220,39 @@ export class InterceptorService extends Http { continue; } - requestWrapper$ = requestWrapper$ - .flatMap((requestWrapper: InterceptorRequestWrapper, index: number) => { - let interceptedRequestInternal = new InterceptorService._InterceptorRequestWrapper(requestWrapper); + request$ = request$ + .flatMap((request: InterceptorRequest, index: number) => { + let interceptorRequestInternal = new InterceptorService._InterceptorRequestBuilder(request); - if (interceptedRequestInternal.err || interceptedRequestInternal.alreadyShortCircuited) { - return Observable.of(requestWrapper); - } else if (interceptedRequestInternal.shortCircuitAtCurrentStep) { - if (interceptedRequestInternal.alsoForceRequestCompletion) { + if (interceptorRequestInternal.err || interceptorRequestInternal.alreadyShortCircuited) { + return Observable.of(request); + } else if (interceptorRequestInternal.shortCircuitAtCurrentStep) { + if (interceptorRequestInternal.alsoForceRequestCompletion) { return Observable.empty(); - } else if (!interceptedRequestInternal.alreadyShortCircuited) { - let requestWrapperBuilder = InterceptorService._InterceptorRequestWrapperBuilder.new(requestWrapper) + } else if (!interceptorRequestInternal.alreadyShortCircuited) { + let requestBuilder = InterceptorService._InterceptorRequestBuilder.new(request) .shortCircuitAtCurrentStep(false) .shortCircuitTriggeredBy(this.interceptors.length - 1) // since the last interceptor in the chain asked for short circuiting .alreadyShortCircuited(true); - return Observable.of(requestWrapperBuilder.build()); + return Observable.of(requestBuilder.build()); } else { - return Observable.of(requestWrapper); + return Observable.of(request); } } - let modifiedRequest = bf.beforeRequest(requestWrapper); - let newInterceptedRequest$: Observable; + let modifiedRequest = bf.beforeRequest(request); + let newInterceptorRequest$: Observable; if (!modifiedRequest) { // if no request is returned; just proceed with the original request - newInterceptedRequest$ = Observable.of(requestWrapper); + newInterceptorRequest$ = Observable.of(request); } else if (modifiedRequest instanceof Observable) { - newInterceptedRequest$ = >modifiedRequest; + newInterceptorRequest$ = >modifiedRequest; } else { - newInterceptedRequest$ = Observable.of(modifiedRequest); + newInterceptorRequest$ = Observable.of(modifiedRequest); } - return newInterceptedRequest$ - .catch((err: any, caught: Observable) => { - let responseBuilder = InterceptorService._InterceptorRequestWrapperBuilder.new(requestWrapper) + return newInterceptorRequest$ + .catch((err: any, caught: Observable) => { + let responseBuilder = InterceptorService._InterceptorRequestBuilder.new(request) .err(err) .errEncounteredAt(i); return Observable.of(responseBuilder.build()); @@ -260,7 +260,7 @@ export class InterceptorService extends Http { }); } - return requestWrapper$; + return request$; } private runAfterInterceptors(responseWrapper: InterceptorResponseWrapper): Observable { @@ -332,12 +332,12 @@ export class InterceptorService extends Http { } /** - * Class that exposes internal variables of InterceptorRequestWrapper for internal use + * Class that exposes internal variables of InterceptorRequest for internal use */ - private static _InterceptorRequestWrapper = class extends InterceptorRequestWrapper { + private static _InterceptorRequest = class extends InterceptorRequest { - constructor(requestWrapper: InterceptorRequestWrapper) { - super(InterceptorRequestWrapperBuilder.new(requestWrapper)); + constructor(request: InterceptorRequest) { + super(InterceptorRequestBuilder.new(request)); } shortCircuitAtCurrentStep(shortCircuitAtCurrentStep: boolean): boolean { @@ -367,21 +367,21 @@ export class InterceptorService extends Http { } /** - * Utility builder for creating a new instance of _InterceptorRequestWrapper with additional ability to set internal properties aswell - * Use _InterceptorRequestWrapperBuilder.new() to instantiate the builder + * Utility builder for creating a new instance of _InterceptorRequest with additional ability to set internal properties aswell + * Use _InterceptorRequestBuilder.new() to instantiate the builder */ - private static _InterceptorRequestWrapperBuilder = class extends InterceptorRequestWrapperBuilder { + private static _InterceptorRequestBuilder = class extends InterceptorRequestBuilder { /** - * Use _InterceptorRequestWrapperBuilder.new() to instantiate the builder + * Use _InterceptorRequestBuilder.new() to instantiate the builder */ protected constructor() { super(); } - static new(requestWrapper?: InterceptorRequestWrapper) { - const builder = new InterceptorService._InterceptorRequestWrapperBuilder(); - InterceptorUtils.assign(builder, requestWrapper); + static new(request?: InterceptorRequest) { + const builder = new InterceptorService._InterceptorRequestBuilder(); + InterceptorUtils.assign(builder, request); return builder; } @@ -445,14 +445,14 @@ export class InterceptorService extends Http { super(); } - static new(from?: Response | InterceptorResponseWrapper | InterceptorRequestWrapper) { + static new(from?: Response | InterceptorResponseWrapper | InterceptorRequest) { const builder = new InterceptorService._InterceptorResponseWrapperBuilder(); if (from instanceof Response) { builder._response = from; } else if (from instanceof InterceptorResponseWrapper) { InterceptorUtils.assign(builder, from); } else { - InterceptorUtils.assign(builder, from); + InterceptorUtils.assign(builder, from); } return builder; } diff --git a/src/interceptor.ts b/src/interceptor.ts index 4d6e35c..51a4bdd 100644 --- a/src/interceptor.ts +++ b/src/interceptor.ts @@ -1,6 +1,6 @@ import { Observable } from 'rxjs/Rx'; -import { InterceptorRequestWrapper } from "./interceptor-request-wrapper"; +import { InterceptorRequest } from "./interceptor-request"; import { InterceptorResponseWrapper } from "./interceptor-response-wrapper"; /** @@ -13,7 +13,7 @@ import { InterceptorResponseWrapper } from "./interceptor-response-wrapper"; * 4. Short circuit complete request flow dynamically based on the dynamic conditions without affecting the actual controller/service * 5. Ability to perform custom logic; such as redirecting the users to login page, if the server returns 401, transparantly without polluting all your services * - * NOTE: Never store any data that's request specific as properties on the Interceptor implementation, as the interceptor instance is shared across all http requests within the application. Instead use `InterceptorRequestOptionsArgs.sharedData` (or) `InterceptorRequestWrapper.sharedData` (or) `InterceptorResponseWrapper.sharedData` as request private storage + * NOTE: Never store any data that's request specific as properties on the Interceptor implementation, as the interceptor instance is shared across all http requests within the application. Instead use `InterceptorRequestOptionsArgs.sharedData` (or) `InterceptorRequest.sharedData` (or) `InterceptorResponseWrapper.sharedData` as request private storage */ export interface Interceptor { @@ -22,7 +22,7 @@ export interface Interceptor { * * Gives the ability to transform the request */ - beforeRequest?(request: InterceptorRequestWrapper, interceptorStep?: number): Observable | InterceptorRequestWrapper | void; + beforeRequest?(request: InterceptorRequest, interceptorStep?: number): Observable | InterceptorRequest | void; /** * Invoked once for each of the interceptors in the chain; in the reverse order of chain, unless any of the earlier interceptors asked to complete the flow/return response/throw error to subscriber @@ -41,7 +41,7 @@ export interface Interceptor { onResponse?(response: InterceptorResponseWrapper, interceptorStep?: number): Observable | InterceptorResponseWrapper | void; /** - * Invoked once for each of the interceptors in the chain; in the reverse order of chain, if any of the `beforeRequest(..)` responded by setting `shortCircuitAtCurrentStep` property of `InterceptorRequestWrapper` + * Invoked once for each of the interceptors in the chain; in the reverse order of chain, if any of the `beforeRequest(..)` responded by setting `shortCircuitAtCurrentStep` property of `InterceptorRequest` * Use this method to generate a response that gets sent to the subscriber. * If you return nothing, the `onShortCircuit(..) will be cascaded along the interceptor chain * If you return an Observable | InterceptorResponseWrapper, this rest of the flow would be continued on `onResponse(..)` instead of `onErr(..)` on the next interceptor in the chain & the final result would be sent to the subscriber via next(..) callback diff --git a/src/real-response-observable-transformer.ts b/src/real-response-observable-transformer.ts index 2632c01..a1cf6dc 100644 --- a/src/real-response-observable-transformer.ts +++ b/src/real-response-observable-transformer.ts @@ -1,6 +1,6 @@ import { Observable } from 'rxjs/Rx'; import { Response } from '@angular/http'; -import { InterceptorRequestWrapper } from './interceptor-request-wrapper'; +import { InterceptorRequest } from './interceptor-request'; /** * Gives access to the `Observable` returned by tha angular `Http` api. @@ -10,5 +10,5 @@ import { InterceptorRequestWrapper } from './interceptor-request-wrapper'; * 2. Allows user to retry the request if the requets is expired due to connection timeout using `Observable.retry`/`Observable.retryWhen` */ export interface RealResponseObservableTransformer { - tranform(response: Observable, request: InterceptorRequestWrapper): Observable; + tranform(response: Observable, request: InterceptorRequest): Observable; } From 09eb787ab4a027fc33a7de3fa77b74d91230b9f8 Mon Sep 17 00:00:00 2001 From: Ashok Koyi Date: Thu, 19 Jan 2017 19:07:45 +0530 Subject: [PATCH 3/8] Made error handling consistent across before & after interceptor execution --- src/interceptor-service.ts | 101 +++++++++++++++++++------------------ 1 file changed, 51 insertions(+), 50 deletions(-) diff --git a/src/interceptor-service.ts b/src/interceptor-service.ts index caa2a60..4721ea1 100644 --- a/src/interceptor-service.ts +++ b/src/interceptor-service.ts @@ -22,8 +22,6 @@ import { InterceptorResponseWrapperBuilder } from './interceptor-response-wrappe import { InterceptorUtils } from './interceptor-utils'; import { RealResponseObservableTransformer } from './real-response-observable-transformer'; -import './object-assign-polyfill'; - /** * Wrapper around native angular `Http` service. * Allows you to add `Interceptor`s that lets you do @@ -215,21 +213,21 @@ export class InterceptorService extends Http { let request$: Observable = Observable.of(params); for (let i: number = 0; i < this.interceptors.length; i++) { - let bf: Interceptor = this.interceptors[i]; - if (!bf.beforeRequest) { + let interceptor: Interceptor = this.interceptors[i]; + if (!interceptor.beforeRequest) { continue; } request$ = request$ .flatMap((request: InterceptorRequest, index: number) => { - let interceptorRequestInternal = new InterceptorService._InterceptorRequestBuilder(request); + let requestInternal = new InterceptorService._InterceptorRequestBuilder(request); - if (interceptorRequestInternal.err || interceptorRequestInternal.alreadyShortCircuited) { + if (requestInternal.err || requestInternal.alreadyShortCircuited) { return Observable.of(request); - } else if (interceptorRequestInternal.shortCircuitAtCurrentStep) { - if (interceptorRequestInternal.alsoForceRequestCompletion) { + } else if (requestInternal.shortCircuitAtCurrentStep) { + if (requestInternal.alsoForceRequestCompletion) { return Observable.empty(); - } else if (!interceptorRequestInternal.alreadyShortCircuited) { + } else if (!requestInternal.alreadyShortCircuited) { let requestBuilder = InterceptorService._InterceptorRequestBuilder.new(request) .shortCircuitAtCurrentStep(false) .shortCircuitTriggeredBy(this.interceptors.length - 1) // since the last interceptor in the chain asked for short circuiting @@ -240,17 +238,17 @@ export class InterceptorService extends Http { } } - let modifiedRequest = bf.beforeRequest(request); - let newInterceptorRequest$: Observable; + let processedRequest = interceptor.beforeRequest(request); + let processedRequest$: Observable; - if (!modifiedRequest) { // if no request is returned; just proceed with the original request - newInterceptorRequest$ = Observable.of(request); - } else if (modifiedRequest instanceof Observable) { - newInterceptorRequest$ = >modifiedRequest; + if (!processedRequest) { // if no request is returned; just proceed with the original request + processedRequest$ = Observable.of(request); + } else if (processedRequest instanceof Observable) { + processedRequest$ = >processedRequest; } else { - newInterceptorRequest$ = Observable.of(modifiedRequest); + processedRequest$ = Observable.of(processedRequest); } - return newInterceptorRequest$ + return processedRequest$ .catch((err: any, caught: Observable) => { let responseBuilder = InterceptorService._InterceptorRequestBuilder.new(request) .err(err) @@ -281,44 +279,47 @@ export class InterceptorService extends Http { continue; } - let lastResponseWrapper: InterceptorResponseWrapper; + responseWrapper$ = responseWrapper$ + .flatMap((responseWrapper: InterceptorResponseWrapper, _: any) => { + if (responseWrapper.forceRequestCompletion) { + return Observable.empty(); + } else if (responseWrapper.forceReturnResponse) { + return Observable.of(responseWrapper); + } - responseWrapper$ = responseWrapper$.flatMap((responseWrapper: InterceptorResponseWrapper, _: any) => { - lastResponseWrapper = responseWrapper; - if (responseWrapper.forceRequestCompletion) { - return Observable.empty(); - } else if (responseWrapper.forceReturnResponse) { - return Observable.of(responseWrapper); - } + let processedResponse; - let processedResponse; + const invokeErrHandler = responseWrapper.err && !responseWrapper.response; + const invokeShortCircuitHandler = responseWrapper.isShortCircuited() && !responseWrapper.response; - const invokeErrHandler = responseWrapper.err && !responseWrapper.response; - const invokeShortCircuitHandler = responseWrapper.isShortCircuited() && !responseWrapper.response; + if (invokeErrHandler) { + processedResponse = interceptor.onErr(responseWrapper); + } else if (invokeShortCircuitHandler) { + processedResponse = interceptor.onShortCircuit(responseWrapper, index); + } else { + processedResponse = interceptor.onResponse(responseWrapper, index); + } - if (invokeErrHandler) { - processedResponse = interceptor.onErr(responseWrapper); - } else if (invokeShortCircuitHandler) { - processedResponse = interceptor.onShortCircuit(responseWrapper, index); - } else { - processedResponse = interceptor.onResponse(responseWrapper, index); - } + let procesedResponseWrapper$: Observable; - if (!processedResponse) { - return Observable.of(responseWrapper); - } else if (processedResponse instanceof InterceptorResponseWrapper) { - return Observable.of(processedResponse as InterceptorResponseWrapper); - } else { - return processedResponse as Observable; - } - }).catch((err: any, _: Observable) => { - let responseBuilder = InterceptorService._InterceptorResponseWrapperBuilder.new(lastResponseWrapper) - .response(undefined) - .err(err) - .errEncounteredAt(index) - .errEncounteredInRequestCycle(false); - return Observable.of(responseBuilder.build()); - }); + if (!processedResponse) { + procesedResponseWrapper$ = Observable.of(responseWrapper); + } else if (processedResponse instanceof InterceptorResponseWrapper) { + procesedResponseWrapper$ = Observable.of(processedResponse as InterceptorResponseWrapper); + } else { + procesedResponseWrapper$ = processedResponse as Observable; + } + + return procesedResponseWrapper$ + .catch((err: any, _: Observable) => { + let responseBuilder = InterceptorService._InterceptorResponseWrapperBuilder.new(responseWrapper) + .response(undefined) + .err(err) + .errEncounteredAt(index) + .errEncounteredInRequestCycle(false); + return Observable.of(responseBuilder.build()); + }) + }); } return responseWrapper$; From 9cece12f211e7793cc604f5ee07e196b92d3026e Mon Sep 17 00:00:00 2001 From: Ashok Koyi Date: Thu, 19 Jan 2017 19:14:36 +0530 Subject: [PATCH 4/8] Removed yarn.lock file, as its as it is a build artifact, not the atucal source --- yarn.lock | 37 ------------------------------------- 1 file changed, 37 deletions(-) delete mode 100644 yarn.lock diff --git a/yarn.lock b/yarn.lock deleted file mode 100644 index bbbd149..0000000 --- a/yarn.lock +++ /dev/null @@ -1,37 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@angular/common@>=4.0.0-beta.1 <5": - version "4.0.0-beta.3" - resolved "https://registry.yarnpkg.com/@angular/common/-/common-4.0.0-beta.3.tgz#da6679ae716dbf934098f3393f45db148eeb1d0b" - -"@angular/core@>=4.0.0-beta.1 <5": - version "4.0.0-beta.3" - resolved "https://registry.yarnpkg.com/@angular/core/-/core-4.0.0-beta.3.tgz#17a09d0fa631edd9c7767ad567bd16aab21898e0" - -"@angular/http@>=4.0.0-beta.1 <5": - version "4.0.0-beta.3" - resolved "https://registry.yarnpkg.com/@angular/http/-/http-4.0.0-beta.3.tgz#0cbc22d164d95d50e408bd14ef0daccaa0801eb2" - -"@angular/platform-browser@>=4.0.0-beta.1 <5": - version "4.0.0-beta.3" - resolved "https://registry.yarnpkg.com/@angular/platform-browser/-/platform-browser-4.0.0-beta.3.tgz#fe68e19a7745c20a8721040f4ea8e17e5289bc02" - -rxjs@^5.0.0: - version "5.0.3" - resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-5.0.3.tgz#fc8bdf464ebf938812748e4196788f392fef9754" - dependencies: - symbol-observable "^1.0.1" - -symbol-observable@^1.0.1: - version "1.0.4" - resolved "https://registry.yarnpkg.com/symbol-observable/-/symbol-observable-1.0.4.tgz#29bf615d4aa7121bdd898b22d4b3f9bc4e2aa03d" - -typescript@^2.0.3: - version "2.1.5" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.1.5.tgz#6fe9479e00e01855247cea216e7561bafcdbcd4a" - -zone.js@^0.6.21: - version "0.6.26" - resolved "https://registry.yarnpkg.com/zone.js/-/zone.js-0.6.26.tgz#067c13b8b80223a89b62e9dc82680f09762c4636" From 914e0111b80f8f4ae8ff6883cec1bd231b953f0a Mon Sep 17 00:00:00 2001 From: Ashok Koyi Date: Thu, 19 Jan 2017 19:15:05 +0530 Subject: [PATCH 5/8] Minor change --- src/interceptor-service.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/interceptor-service.ts b/src/interceptor-service.ts index 4721ea1..c2b482e 100644 --- a/src/interceptor-service.ts +++ b/src/interceptor-service.ts @@ -143,12 +143,15 @@ export class InterceptorService extends Http { } /** - * Adds this interceptor + * Appends this interceptor to the list of interceptors */ addInterceptor(interceptor: Interceptor) { this.interceptors.push(interceptor); } + /** + * Sets response transformer + */ set realResponseObservableTransformer(value: RealResponseObservableTransformer) { this._realResponseObservableTransformer = value; } From 62b26f59ad45b234321521c650e151df6384f4db Mon Sep 17 00:00:00 2001 From: Ashok Koyi Date: Thu, 19 Jan 2017 19:27:26 +0530 Subject: [PATCH 6/8] Modified package.json to support version 2, since the branch name is 2.0.0, implying angular2, its better to name the artifact aswell with ng2, so that the releases will be future proofed --- README.md | 12 ++++++------ package.json | 20 ++++++++++---------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 204ef49..50a287b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# ng-http-interceptor +# ng2-http-interceptor This package adds the intercepting capabilities to `http` module of Angular 2+, by extending the @angular/http class. For concept behind Interceptor, take a look at the [wiki](https://github.com/voliva/angular2-interceptors/wiki/Concept) @@ -7,7 +7,7 @@ This package adds the intercepting capabilities to `http` module of Angular 2+, To install, just run in your angular project: ``` -npm install ng-http-interceptor --save +npm install ng2-http-interceptor --save ``` And it should be importable with webpack out of the box @@ -19,7 +19,7 @@ Interceptors are registered when the service is created (to avoid any race-condi ```ts import { XHRBackend, RequestOptions } from '@angular/http'; -import { InterceptorService } from 'ng-http-interceptor'; +import { InterceptorService } from 'ng2-http-interceptor'; export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions) { let service = new InterceptorService(xhrBackend, requestOptions); @@ -50,7 +50,7 @@ export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: Reque Once we have it set up, we can use it in our Controllers as if we were using the default Angular `Http` service: ```ts import { Component } from '@angular/core'; -import { InterceptorService } from 'ng-http-interceptor'; +import { InterceptorService } from 'ng2-http-interceptor'; @Component({ selector: 'my-component', @@ -148,7 +148,7 @@ export interface Interceptor { One that will get the request that's about to be sent to the server, and another that will get the response that the server just sent. For that, we just need to create a new class that implements Interceptor: ```ts -import { Interceptor, InterceptorRequest, InterceptorResponseWrapper } from 'ng-http-interceptor'; +import { Interceptor, InterceptorRequest, InterceptorResponseWrapper } from 'ng2-http-interceptor'; export class ServerURLInterceptor implements Interceptor { beforeRequest(request: InterceptorRequest): Observable | InterceptorRequest | void { @@ -216,7 +216,7 @@ If you are using the `provideInterceptorService` option (without AoT Compiler su If our `ServerURLInterceptor` were a Service, we would have a module declaration like: ```ts -import { InterceptorService } from 'ng-http-interceptor'; +import { InterceptorService } from 'ng2-http-interceptor'; import { ServerURLInterceptor } from './services/serverURLInterceptor'; import { XHRBackend, RequestOptions } from '@angular/http'; diff --git a/package.json b/package.json index 6f111d2..ab5c695 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { - "name": "ng-http-interceptor", - "version": "2.0.0", + "name": "ng2-http-interceptor", + "version": "1.0.0", "description": "Angular2 interceptor service implementation", "keywords": [ "Angular 2", @@ -25,17 +25,17 @@ "build": "rimraf lib && tsc -p src" }, "peerDependencies": { - "@angular/core": ">=4.0.0-beta.1 <5", - "@angular/http": ">=4.0.0-beta.1 <5", + "@angular/core": "^2.0.0", + "@angular/http": "^2.0.0", "rxjs": "^5.0.0" }, "devDependencies": { - "@angular/common": ">=4.0.0-beta.1 <5", - "@angular/core": ">=4.0.0-beta.1 <5", - "@angular/http": ">=4.0.0-beta.1 <5", - "@angular/platform-browser": ">=4.0.0-beta.1 <5", - "rxjs": "^5.0.3", - "typescript": "^2.1.5", + "@angular/common": "^2.0.0", + "@angular/core": "^2.0.0", + "@angular/http": "^2.0.0", + "@angular/platform-browser": "^2.0.0", + "rxjs": "^5.0.0", + "typescript": "^2.0.0", "zone.js": "^0.6.26" } } From edfcfe66c82821fca0b8eb0c4a53fcc3c9b596f7 Mon Sep 17 00:00:00 2001 From: Ashok Koyi Date: Thu, 19 Jan 2017 19:50:14 +0530 Subject: [PATCH 7/8] Spelling change --- src/interceptor-service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/interceptor-service.ts b/src/interceptor-service.ts index c2b482e..7cc033f 100644 --- a/src/interceptor-service.ts +++ b/src/interceptor-service.ts @@ -203,7 +203,7 @@ export class InterceptorService extends Http { if (responseWrapper.err) { return Observable.throw(responseWrapper.err); } else if (responseWrapper.isShortCircuited()) { - return Observable.throw(new Error('Short circuit was triggere, but no short circuit handlers generated any resonse')); + return Observable.throw(new Error('Short circuit was triggered, but no short circuit handlers generated any resonse')); } else { return Observable.throw(new Error('Response is empty')); } From 18055cecab6d3f9f3b9e31316fc44e3eabab4f44 Mon Sep 17 00:00:00 2001 From: Ashok Koyi Date: Fri, 20 Jan 2017 17:24:41 +0530 Subject: [PATCH 8/8] Now tranformer callback will get both the interceptor service & `HttpDirect` which gives access to http API bypassing interception --- .gitignore | 1 + index.d.ts | 1 + index.js | 1 + package.json | 10 +-- src/http-direct.ts | 14 ++++ src/interceptor-response-wrapper.ts | 8 +++ src/interceptor-service.ts | 79 ++++++++++++++++++++- src/real-response-observable-transformer.ts | 8 ++- 8 files changed, 115 insertions(+), 7 deletions(-) create mode 100644 src/http-direct.ts diff --git a/.gitignore b/.gitignore index 0d78a3c..92bfdad 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ node_modules/ *.log yarn.lock *.js +*.*~ diff --git a/index.d.ts b/index.d.ts index ab41efd..522ca09 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,3 +1,4 @@ +export { HttpDirect } from "./lib/http-direct"; export { InterceptorRequestBuilder } from "./lib/interceptor-request-builder"; export { InterceptorRequestOptionsArgs } from "./lib/interceptor-request-options-args"; export { InterceptorRequest } from "./lib/interceptor-request"; diff --git a/index.js b/index.js index 426b40e..b333fb0 100644 --- a/index.js +++ b/index.js @@ -1,3 +1,4 @@ +exports.HttpDirect = require('./lib/http-direct').HttpDirect; exports.InterceptorRequestBuilder = require('./lib/interceptor-request-builder').InterceptorRequestBuilder; exports.InterceptorRequestOptionsArgs = require('./lib/interceptor-request-options-args').InterceptorRequestOptionsArgs; exports.InterceptorRequest = require('./lib/interceptor-request').InterceptorRequest; diff --git a/package.json b/package.json index ab5c695..0e27a98 100644 --- a/package.json +++ b/package.json @@ -11,10 +11,12 @@ "name": "Víctor Oliva", "email": "olivarra1@gmail.com" }, - "contributors": [{ - "name": "Ashok Koyi", - "url": "http://thekalinga.in" - }], + "contributors": [ + { + "name": "Ashok Koyi", + "url": "http://thekalinga.in" + } + ], "repository": { "type": "git", "url": "https://github.com/voliva/angular2-interceptors" diff --git a/src/http-direct.ts b/src/http-direct.ts new file mode 100644 index 0000000..8652b6e --- /dev/null +++ b/src/http-direct.ts @@ -0,0 +1,14 @@ +import { Request, RequestOptionsArgs, Response } from '@angular/http'; + +import { Observable } from 'rxjs/Rx'; + +export interface HttpDirect { + request(url: string | Request, options?: RequestOptionsArgs): Observable; + get(url: string, options?: RequestOptionsArgs): Observable; + post(url: string, body: any, options?: RequestOptionsArgs): Observable; + put(url: string, body: any, options?: RequestOptionsArgs): Observable; + delete(url: string, options?: RequestOptionsArgs): Observable; + patch(url: string, body: any, options?: RequestOptionsArgs): Observable; + head(url: string, options?: RequestOptionsArgs): Observable; + options(url: string, options?: RequestOptionsArgs): Observable; +} diff --git a/src/interceptor-response-wrapper.ts b/src/interceptor-response-wrapper.ts index 3468dfe..1247710 100644 --- a/src/interceptor-response-wrapper.ts +++ b/src/interceptor-response-wrapper.ts @@ -72,6 +72,14 @@ export class InterceptorResponseWrapper { */ protected _errEncounteredInRequestCycle?: boolean; + get url(): string | Request { + return this._url; + } + + get options(): any { + return this._options; + } + get response(): Response { return this._response; } diff --git a/src/interceptor-service.ts b/src/interceptor-service.ts index 7cc033f..541dbd4 100644 --- a/src/interceptor-service.ts +++ b/src/interceptor-service.ts @@ -13,6 +13,7 @@ import { RequestOptionsArgs } from '@angular/http/src/interfaces'; import { Observable, Observer } from 'rxjs/Rx'; import { ErrorObservable } from 'rxjs/observable/ErrorObservable'; +import { HttpDirect } from './http-direct'; import { InterceptorRequest } from './interceptor-request'; import { InterceptorResponseWrapper } from './interceptor-response-wrapper'; import { Interceptor } from './interceptor'; @@ -180,7 +181,7 @@ export class InterceptorService extends Http { let response$ = super.request(request.url, request.options); if (this._realResponseObservableTransformer) { - response$ = this._realResponseObservableTransformer.tranform(response$, request); + response$ = this._realResponseObservableTransformer.tranform(response$, request, new this.HttpDirect(), this); } return response$.map((response: Response) => { @@ -518,4 +519,80 @@ export class InterceptorService extends Http { } + /** + * Returns an implementation that mirrors angular `Http` interface; + * This interface allows the response transformers to make calls directly to HTTP calls without being interceted by {@code InterceptorService}; i.e `this` + */ + private get HttpDirect() { + let interceptorService = this; + + return class implements HttpDirect { + + request(url: string | Request, options?: RequestOptionsArgs): Observable { + return interceptorService.requestNative(url, options); + } + + get(url: string, options?: RequestOptionsArgs): Observable { + return interceptorService.getNative(url, options); + } + + post(url: string, body: any, options?: RequestOptionsArgs): Observable { + return interceptorService.postNative(url, body, options); + } + + put(url: string, body: any, options?: RequestOptionsArgs): Observable { + return interceptorService.putNative(url, body, options); + } + + delete(url: string, options?: RequestOptionsArgs): Observable { + return interceptorService.deleteNative(url, options); + } + + patch(url: string, body: any, options?: RequestOptionsArgs): Observable { + return interceptorService.patchNative(url, body, options); + } + + head(url: string, options?: RequestOptionsArgs): Observable { + return interceptorService.headNative(url, options); + } + + options(url: string, options?: RequestOptionsArgs): Observable { + return interceptorService.optionsNative(url, options); + } + + }; + } + + private requestNative(url: string | Request, options?: RequestOptionsArgs): Observable { + return super.request(url, options); + } + + private getNative(url: string, options?: RequestOptionsArgs): Observable { + return super.get(url, options); + } + + private postNative(url: string, body: any, options?: RequestOptionsArgs): Observable { + return super.post(url, body, options); + } + + private putNative(url: string, body: any, options?: RequestOptionsArgs): Observable { + return super.put(url, body, options); + } + + private deleteNative(url: string, options?: RequestOptionsArgs): Observable { + return super.delete(url, options); + } + + private patchNative(url: string, body: any, options?: RequestOptionsArgs): Observable { + return super.patch(url, body, options); + } + + private headNative(url: string, options?: RequestOptionsArgs): Observable { + return super.head(url, options); + } + + private optionsNative(url: string, options?: RequestOptionsArgs): Observable { + return super.options(url, options); + } + } diff --git a/src/real-response-observable-transformer.ts b/src/real-response-observable-transformer.ts index a1cf6dc..db94472 100644 --- a/src/real-response-observable-transformer.ts +++ b/src/real-response-observable-transformer.ts @@ -1,6 +1,10 @@ -import { Observable } from 'rxjs/Rx'; import { Response } from '@angular/http'; + +import { Observable } from 'rxjs/Rx'; + +import { HttpDirect } from './http-direct'; import { InterceptorRequest } from './interceptor-request'; +import { InterceptorService } from './interceptor-service'; /** * Gives access to the `Observable` returned by tha angular `Http` api. @@ -10,5 +14,5 @@ import { InterceptorRequest } from './interceptor-request'; * 2. Allows user to retry the request if the requets is expired due to connection timeout using `Observable.retry`/`Observable.retryWhen` */ export interface RealResponseObservableTransformer { - tranform(response: Observable, request: InterceptorRequest): Observable; + tranform(response$: Observable, request: InterceptorRequest, http: HttpDirect, interceptorService: InterceptorService): Observable; }