Hullo JS
Search…
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:
1
import { fetch } from "@hullo/browser";
2
​
3
fetch(
4
new Request(
5
"http://example.com/api",
6
{ method: "GET", cache: "no-cache" }
7
)
8
)
9
.withJSON()
10
.subscribe({
11
next(response) {
12
switch (response.status) {
13
case 200:
14
if (
15
typeof response.json === "object" &&
16
response.json &&
17
"ok" in response.json
18
) {
19
console.log(response.json.ok);
20
}
21
break;
22
case 404:
23
console.log(response.json);
24
break;
25
}
26
}
27
});
Copied!
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.
Last modified 1yr ago
Copy link