@zakkudo/fetch v1.0.1
@zakkudo/fetch
Make using native fetch enjoyable.
Why use this?
- Consistancy with simplicity
- Automatically parses JSON payloads when the content type of the response is
application/json
- Automatically serializes json in the request body
- Network errors throw an HttpError exception with the exception information for handling
- Interpolates params into url templates.
/users/:id/detail
+{params: {id: "joe"}}
=/users/joe/detail
- Complex params are automatically JSON serialized similar to
@zakkudo/query-string
- Proper
transformRequest
/transformResponse
/transformError
hooks
Install
# Install using npm
npm install @zakkudo/fetch
# Install using yarn
yarn add @zakkudo/fetch
Examples
Post to an endpoint
import fetch from '@zakkudo/fetch';
//Create a user
fetch('http://example.com/users', {
method: 'POST'
body: {
first_name: 'joe',
last_name: 'johnson',
},
}).then((reponse) => {
console.log(response); // {'id': '1234'}
}.catch((reason) => {
if (reason.status === 401) {
return authenticate();
}
console.error(reason);
throw reason;
});
Get data from an endpoint
import fetch from '@zakkudo/fetch';
//Fetch the created user
fetch('http://example.com/users/:id', {
params: {
id: '1234'
},
}).then((reponse) => {
console.log(response); // {id: '1234', first_name: 'joe', last_name: 'johnson'}
}.catch((reason) => {
if (reason.status === 401) {
return authenticate();
}
console.error(reason);
throw reason;
});
Transform everything everywhere
import fetch from '@zakkudo/fetch';
//Fetch the created user
fetch('http://example.com/users/:id', {
transformRequest(options) {
return encodeWithJWT(options);
},
transformResponse(response) {
const {first_name, last_name} = response;
response.full_name = `${first_name} ${last_name}`;
return response;
},
transformError(reason) {
if (reason.status === 401) {
window.href = '/login';
}
return reason;
},
params: {
id: '1234'
},
}).then((reponse) => {
console.log(response); // {id: '1234', first_name: 'joe', last_name: 'johnson', full_name': 'joe johnson'}
});
Handling errors
import fetch from '@zakkudo/fetch';
import HttpError from '@zakkudo/fetch/HttpError';
fetch('http://example.com/does-not-exist').catch((reason) => {
if (reason instanceof HttpError) {
console.log(reason.status); // 404
}
});
Use with async/await
import fetch from '@zakkudo/fetch';
import HttpError from '@zakkudo/fetch/HttpError';
async function get() {
try {
const response = await fetch('http://example.com/does-not-exist');
console.log(response);
} catch (e) {
if (e instanceof HttpError) {
console.log(e.status); // 404
}
}
}
API
@zakkudo/fetch~fetch(url, options) ⇒ Promise ⏏
Kind: Exported function
Returns: Promise - Resolves to the response of the network transaction or rejects with an HttpError
Throws:
- HttpError For errors during the network transaction
- UrlError For incorrectly formatted urls
- QueryStringError On issues during serialization or construction of the query string
Param | Type | Description |
---|---|---|
url | String | The request url |
options | Options | Options modifying the network call, mostly analogous to fetch |
fetch~Options : Object
Options modifying the network call, mostly analogous to fetch
Kind: inner typedef of fetch
Properties
Name | Type | Default | Description |
---|---|---|---|
options.method | String | 'GET' | GET, POST, PUT, DELETE, etc. |
options.mode | String | 'same-origin' | no-cors, cors, same-origin |
options.cache | String | 'default' | default, no-cache, reload, force-cache, only-if-cached |
options.credentials | String | 'omit' | include, same-origin, omit |
options.headers | String | "application/json; charset=utf-8". | |
options.redirect | String | 'follow' | manual, follow, error |
options.referrer | String | 'client' | no-referrer, client |
options.body | String | Object | JSON.stringify is automatically run for non-string types | |
options.params | String | Object | Query params to be appended to the url. The url must not already have params. The serialization uses the same rules as used by @zakkudo/query-string | |
options.transformRequest | function | Array.<function()> | Transforms for the request body. When not supplied, it by default json serializes the contents if not a simple string. Also accepts promises as return values for asynchronous work. | |
options.unsafe | Boolean | Disable escaping of params in the url | |
options.transformResponse | function | Array.<function()> | Transform the response. Also accepts promises as return values for asynchronous work. | |
options.transformError | function | Array.<function()> | Transform the error response. Return the error to keep the error state. Return a non Error to recover from the error in the promise chain. A good place to place a login handler when recieving a 401 from a backend endpoint or redirect to another page. It's preferable to never throw an error here which will break the error transform chain in a non-graceful way. Also accepts promises as return values for asynchronous work. |
@zakkudo/fetch/HttpError~HttpError ⇐ Error ⏏
An error representing an HTTP error during a network connection.
Kind: Exported class
Extends: Error
- ~HttpError ⇐ Error
new HttpError(status, statusText, url, headers, response)
Param | Type | Description |
---|---|---|
status | Integer | The http error code |
statusText | String | The string representation of the error |
url | String | The url that failed |
headers | Object | The headers when the request failed |
response | * | The response of the transaction. Determined arbitraility by the server. Can be deserialized json. |
httpError.status
The http error code
Kind: instance property of HttpError
httpError.statusText
The string representation of the error
Kind: instance property of HttpError
httpError.url
The url that failed
Kind: instance property of HttpError
httpError.headers
The headers when the request failed
Kind: instance property of HttpError
httpError.response
The response of the transaction. Determined arbitraility by the server. Can be deserialized json.
Kind: instance property of HttpError
@zakkudo/fetch/UrlError~UrlError ⏏
Aliased error from package @zakkudo/url/UrlError
Kind: Exported class
@zakkudo/fetch/QueryStringError~QueryStringError ⏏
Aliased error from package @zakkudo/url/QueryStringError
Kind: Exported class