Skip to content

Commit

Permalink
feat($interceptor): Added support handling request cancellations
Browse files Browse the repository at this point in the history
If the user unsubscribes while the request is still being handled, interceptor can now implement
`onUnsubscribe` method to perform any cleaup operations
  • Loading branch information
thekalinga committed May 23, 2017
1 parent 04085a7 commit 881506d
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 24 deletions.
72 changes: 51 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,13 @@ Basically, an interceptor has the option to selectively implement one more of th
Here is the interceptor interface that details which method is invoked in what part of the flow

```ts
import { Request, RequestOptionsArgs } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import { InterceptorRequest } from './interceptor-request';
import { InterceptorRequestOptionsArgs } from './interceptor-request-options-args';
import { InterceptorResponseWrapper } from './interceptor-response-wrapper';

/**
* Represents an intermediary in the interceptor chain that intercept both HTTP request & response flow
*
Expand All @@ -101,52 +108,75 @@ Here is the interceptor interface that details which method is invoked in what p
* 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
* 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
* 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
* 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> | InterceptorRequest | void;
beforeRequest?(request: InterceptorRequest, interceptorStep: number): Observable<InterceptorRequest> | 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
* 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/short the circuit/return response/throw error to subscriber
*
* 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
* 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> | InterceptorResponseWrapper | void;
onResponse?(response: InterceptorResponseWrapper,
interceptorStep: number): Observable<InterceptorResponseWrapper> | 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`
* 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> | 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
* The result returned by the first interceptor(last in the response flow) would be sent to the subscriber via next(..) callback
* If no `onShortCircuit(..)` handlers before this handler returns any response/force request to complete
* An error will be thrown back to the subscriber
*/
onShortCircuit?(response: InterceptorResponseWrapper, interceptorStep?: number): Observable<InterceptorResponseWrapper> | InterceptorResponseWrapper | void;
onShortCircuit?(response: InterceptorResponseWrapper,
interceptorStep: number): Observable<InterceptorResponseWrapper> | 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.
* Use this method to generate a response that gets sent to the subscriber. `response.err` will contain th actual error
* If you return nothing, the `onErr(..) will be cascaded along the interceptor chain
* If you return an Observable<InterceptorResponseWrapper> | 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
* If you return an Observable<InterceptorResponseWrapper> | InterceptorResponseWrapper
* & the final interceptor in the result chain (first interceptor) would be sent to the subscriber via next(..) callback
* If no `onErr(..)` handlers before the first interceptor (last in the response cycle)
* handler returns any response, the error will be thrown back to the subscriber
*/
onErr?(response: InterceptorResponseWrapper,
interceptorStep: number): Observable<InterceptorResponseWrapper> | InterceptorResponseWrapper | void;

/**
* Invoked when any one in the interceptor chain forces request completion/return response/error
* Use this method to perform operations that should be performed irrespective of what the other interceptors in the chain does
* such as stopping progress bar/logging
*/
onForceCompleteOrForceReturn?(response: InterceptorResponseWrapper,
interceptorStep: number): void;

/**
* Invoked when the user unsubscribes while the request is still being handled
* Use this method to perform cleanup operations that should be performed when the request is cancelled by user
* such as stopping progress bar
*/
onErr?(err: any): Observable<InterceptorResponseWrapper> | InterceptorResponseWrapper | void;
onUnsubscribe?(interceptorStep: number, url: string | Request, options?: RequestOptionsArgs | InterceptorRequestOptionsArgs): void;

}
```
Expand Down
17 changes: 15 additions & 2 deletions src/interceptor-service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Subscriber } from 'rxjs/Rx';
import { InterceptorRequestInternal } from './interceptor-request-internal';
import {
ConnectionBackend,
Expand Down Expand Up @@ -50,7 +51,7 @@ import { RealResponseObservableTransformer } from './real-response-observable-tr
*/
export class InterceptorService extends Http {

private interceptors: Array<Interceptor>;
private interceptors: Interceptor[];
private _realResponseObservableTransformer: RealResponseObservableTransformer;

constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
Expand All @@ -75,7 +76,19 @@ export class InterceptorService extends Http {
.options(interceptorOptions)
.sharedData(interceptorOptions.sharedData || {})
.build();
return this.httpRequest(request);
return Observable.create(function (observer: Subscriber<Response>) {
const subscription = this.httpRequest(request).subscribe(
(response: Response) => observer.next(response),
(e: Error) => observer.error(e),
() => observer.complete()
);
observer.add(() => {
this.interceptors.reverse().forEach((interceptor: Interceptor, index: number) => {
interceptor.onUnsubscribe(index, url, options);
});
});
return this;
});
}

/**
Expand Down
11 changes: 10 additions & 1 deletion src/interceptor.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Request, RequestOptionsArgs } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import { InterceptorRequest } from './interceptor-request';
import { InterceptorRequestOptionsArgs } from './interceptor-request-options-args';
import { InterceptorResponseWrapper } from './interceptor-response-wrapper';

/**
Expand Down Expand Up @@ -68,10 +70,17 @@ export interface Interceptor {

/**
* Invoked when any one in the interceptor chain forces request completion/return response/error
* Use this method to perform opeations that should be performed irrespective of what the interceptors in the chain want
* Use this method to perform operations that should be performed irrespective of what the other interceptors in the chain does
* such as stopping progress bar/logging
*/
onForceCompleteOrForceReturn?(response: InterceptorResponseWrapper,
interceptorStep: number): void;

/**
* Invoked when the user unsubscribes while the request is still being handled
* Use this method to perform cleanup operations that should be performed when the request is cancelled by user
* such as stopping progress bar
*/
onUnsubscribe?(interceptorStep: number, url: string | Request, options?: RequestOptionsArgs | InterceptorRequestOptionsArgs): void;

}

0 comments on commit 881506d

Please sign in to comment.