@swan-io/request
Wrapper for XMLHttpRequest with better data-structures
Installation
$ yarn add @swan-io/request @swan-io/boxed
$ npm install --save @swan-io/request @swan-io/boxed
Design principles
- Has a strong contract with data-structures from Boxed (
Future
, Result
& Option
) - Makes the request easily cancellable with
Future
API - Gives freedom of interpretation for response status
- Handles timeouts
- Types the response using the provided
type
Getting started
import { Request, badStatusToError, emptyToError } from "@swan-io/request";
Request.make({ url: "/api/health" }).onResolve(console.log);
Request.make({ url: "/api/health", timeout: 2000 }).onResolve(console.log);
Request.make({ url: "/api/health" }).onResolve(console.log);
Request.make({ url: "/api/health", responseType: "json" }).onResolve(
console.log,
);
Request.make({ url: "/api/health" })
.mapOkToResult(emptyToError)
.onResolve(console.log);
Request.make({ url: "/api/health" })
.mapOkToResult(badStatusToError)
.onResolve(console.log);
useEffect(() => {
const future = Request.make({ url: "/api/health" });
return () => future.cancel();
}, []);
API
Request.make(config)
config
url
: stringmethod
: GET
(default), POST
, OPTIONS
, PATCH
, PUT
or DELETE
type
:
text
: (default) response will be a string
arraybuffer
: response will be a ArrayBuffer
blob
: response will be Blob
json
: response will be a JSON value
body
: request bodyheaders
: a record containing the headerscreatials
: omit
, same-origin
or include
onLoadStart
: event triggered on load starttimeout
: number
Return value
Returns a Future<Result<Response<T>, NetworkError | TimeoutError>>
, where Response<T>
has the following properties:
status
: number
ok
: boolean
response
: Option<T>
xhr
: XMLHttpRequest
T
is the type associated with the responseType
provided in the config
object.
emptyToError
Helper to use with mapOkToResult
to consider empty response as an error.
badStatusToError
Helper to use with mapOkToResult
to consider a status outside of the 200-299 range as an error.