Last active
January 28, 2017 11:55
-
-
Save diestrin/d9320064bf016cfd25210bb0452bb42a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NgModule, Injectable } from '@angular/core'; | |
import { | |
Request, | |
Response, | |
XHRBackend, | |
JSONPBackend, | |
RequestMethod | |
} from '@angular/http'; | |
import { | |
NodeBackend, | |
NodeConnection, | |
NodeJsonpBackend_, | |
NodeJSONPConnection | |
} from 'angular2-platform-node'; | |
import { Observable } from 'rxjs/Observable'; | |
import { _throw } from 'rxjs/observable/throw'; | |
import 'rxjs/add/operator/catch'; | |
import 'rxjs/add/operator/timeout'; | |
const TIMEOUT = 2000; | |
function addTimeout( | |
observable: Observable<Response>, | |
request: Request, | |
method: string | |
) { | |
return observable | |
.timeout(TIMEOUT, new Error(`ERR${method}TIMEOUT`)) | |
.catch(err => { | |
if (err.message === `ERR${method}TIMEOUT`) { | |
console.log(method, 'Server Request Timeout', | |
RequestMethod[request.method], request.url); | |
} | |
return _throw(err); | |
}); | |
}; | |
@Injectable() | |
class XHRWithTimeoutBackend extends NodeBackend { | |
public createConnection(request: Request): NodeConnection { | |
const connection = super.createConnection(request); | |
connection.response = addTimeout(connection.response, request, 'XHR'); | |
return connection; | |
} | |
} | |
@Injectable() | |
class JSONPWithTimeoutBackend extends NodeJsonpBackend_ { | |
public createConnection(request: Request): NodeJSONPConnection { | |
const connection = super.createConnection(request); | |
connection.response = addTimeout(connection.response, request, 'JSONP'); | |
return connection; | |
} | |
} | |
@NgModule({ | |
providers: [ | |
{ provide: XHRBackend, useClass: XHRWithTimeoutBackend }, | |
{ provide: JSONPBackend, useClass: JSONPWithTimeoutBackend } | |
] | |
}) | |
export class HTTPTimeoutModule { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment