fetch

import { fetch } from '@hullo/browser'

This is an adapter for a fetch function available with windowobject. 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 json property to the response object. It will be of type depending on status and status-to-response object provided as a generic argument to fetch function.

withText

Adds text property to the response object.

withArrayBuffer

Adds response body as ArrayBuffer in arrayBuffer property in the response object.

withBlob

Adds response body as Blob in blob property in the response object.

withFormData

Adds response body as FormData in formData property in the response object.

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.