2.0.0 • Published 10 months ago
@swan-io/request v2.0.0
@swan-io/request
Wrapper for XMLHttpRequest with better data-structures
Installation
$ yarn add @swan-io/request @swan-io/boxed
# --- or ---
$ npm install --save @swan-io/request @swan-io/boxedDesign principles
- Has a strong contract with data-structures from Boxed (
Future,Result&Option) - Makes the request easily cancellable with
FutureAPI - 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";
// Regular case
Request.make({ url: "/api/health" }).onResolve(console.log);
// Result.Ok({status: 200, ok: true, response: Option.Some("{\"ok\":true}")})
// Timeout
Request.make({ url: "/api/health", timeout: 2000 }).onResolve(console.log);
// Result.Error(TimeoutError)
// Network error
Request.make({ url: "/api/health" }).onResolve(console.log);
// Result.Error(NetworkError)
// Custom response type
Request.make({ url: "/api/health", responseType: "json" }).onResolve(
console.log,
);
// Result.Ok({status: 200, ok: true, response: Option.Some({ok: true})})
// Handle empty response as an error
Request.make({ url: "/api/health" })
.mapOkToResult(emptyToError)
.onResolve(console.log);
// Result.Error(EmptyResponseError)
// Handle bad status as an error
Request.make({ url: "/api/health" })
.mapOkToResult(badStatusToError)
.onResolve(console.log);
// Result.Error(BadStatusError)
// Cancel request
useEffect(() => {
const future = Request.make({ url: "/api/health" });
return () => future.cancel();
}, []);API
Request.make(config)
config
url: stringmethod:GET(default),POST,OPTIONS,PATCH,PUTorDELETEtype:text: (default) response will be astringarraybuffer: response will be aArrayBufferblob: response will beBlobjson: response will be a JSON value
body: request bodyheaders: a record containing the headerscreatials:omit,same-originorincludeonLoadStart: event triggered on load starttimeout: number
Return value
Returns a Future<Result<Response<T>, NetworkError | TimeoutError>>, where Response<T> has the following properties:
status:numberok:booleanresponse: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.