HttpBackend
Abstract base class for all HTTP backends. A backend receives a prepared request and returns an Observable<HttpEvent>. Swapping the backend changes the transport layer without touching the client or any application code.
@opra/client ships with FetchBackend. @opra/angular provides AngularBackend. Extend HttpBackend to build your own.
Class
abstract class HttpBackend extends Backend {
readonly serviceUrl: string;
interceptors?: HttpInterceptor<any>[];
abstract handle(init: HttpBackend.RequestInit): Observable<HttpEvent>;
}
Constructor
protected constructor(serviceUrl: string, options?: HttpBackend.Options)
The serviceUrl is normalized: trailing slash is added if missing, query string and fragment are stripped.
Properties
| Property | Type | Description |
|---|---|---|
serviceUrl | string | Normalized base URL |
interceptors | HttpInterceptor[] | Interceptors applied before the request reaches the transport |
Abstract method: handle(init)
Implement this to define the transport. Emit events as the request progresses and complete the observable when done.
abstract handle(init: HttpBackend.RequestInit): Observable<HttpEvent>
Custom backend example
import { HttpBackend, HttpClientBase, HttpEventType, HttpResponse } from '@opra/client';
import { Observable } from 'rxjs';
class MockBackend extends HttpBackend {
private fixtures = new Map<string, any>();
fixture(path: string, body: any) {
this.fixtures.set(path, body);
return this;
}
handle(init: HttpBackend.RequestInit): Observable<HttpEvent> {
return new Observable(subscriber => {
const url = new URL(init.url, this.serviceUrl);
const body = this.fixtures.get(url.pathname) ?? null;
subscriber.next({
type: HttpEventType.Response,
request: init,
response: new HttpResponse({ status: body ? 200 : 404, body }),
});
subscriber.complete();
});
}
}
class MockClient extends HttpClientBase {
readonly backend: MockBackend;
constructor(serviceUrl = 'http://localhost') {
const backend = new MockBackend(serviceUrl);
super(backend);
this.backend = backend;
}
}
Interfaces
HttpBackend.Options
interface Options extends Backend.Options {
document?: ApiDocument;
}
HttpBackend.RequestInit
interface RequestInit extends Backend.RequestInit {
method: string;
url: string | URL;
headers?: Headers;
body?: any;
}
See also
FetchBackend— default backend using browser/NodefetchHttpClientBase— accepts anyHttpBackend