This is an adapter for a fetch
function available with window
object. It adds very thin layer of code, but it will be more accurate with type system and usage of unknown
instead of any
.
Take this for example:
import { fetch } from "@hullo/browser";​fetch(new Request("http://example.com/api",{ method: "GET", cache: "no-cache" })).withJSON().subscribe({next(response) {switch (response.status) {case 200:if (typeof response.json === "object" &&response.json &&"ok" in response.json) {console.log(response.json.ok);}break;case 404:console.log(response.json);break;}}});
Fetch alone returns an observable releasing a single object made with status
, statusText
and headers
. To get to the response body, you must pick a fetch with a body parser. This is what withJSON
and alike properties are.
decorator | decoration |
withJSON | Adds |
withText | Adds |
withArrayBuffer | Adds response body as |
withBlob | Adds response body as |
withFormData | Adds response body as |
The module also exports shorthands created after decorators fetchWithJSON
etc.
Because fetch
uses single argument and returns an Observable
, it can be used as an operator.