fetch-compose
v1.0.1
Published
Higher-order functions for WHATWG Fetch. Also includes an opinionated default.
Downloads
248
Readme
fetch-compose
Higher-order functions for WHATWG Fetch. Also includes an opinionated default.
Re-exports the great vercel/fetch-retry library as withRetry
and TypeScript support.
Re-exports the also great cross-fetch as fetch
.
Re-exports the also also great abortcontroller-polyfill as AbortController
only if a system implementation (globalThis.AbortController
) is not provided. Otherwise,
the AbortController
export will equal globalThis.AbortController
, making it safe it use.
Installing
yarn add fetch-compose
Using yarn
is highly recommended but not required.
Motivation
When compared to axios
or request
, the Fetch API is a standard that is
supported across browsers. By using the cross-fetch
package (which fetch-compose
does),
React Native and Node.js become supported platforms as well.
However, compared to those other options, the Fetch API has less out-of-the-box functionality. Using JSON data requires constantly setting HTTP headers, additional boilerplate to check if a request was actually successful, etc.
fetch-compose
expands on the concept of higher-order functions
to transform the Fetch API into being extensible and approachable.
fetch-compose
also includes an opinionated default that covers most use-cases.
Example
Default
Most users will want to use the "batteries-included" default. An example is below.
./src/fetch.js
:
import createFetch from 'fetch-compose'
// Includes JSON, 'query' parameter, throwing an exception on non-ok, and a timeout with default of 10s.
const fetch = createFetch()
export default fetch
./src/App.js
:
import fetch from './fetch'
// ...
// Use Fetch API like normal, just with sugar!
fetch('/api/createUser', {
method: 'POST',
body: {
name: 'Michael',
},
query: {
apikey: 'abc'
}
})
// ...
Default w/ Retry
./src/fetch.js
:
import createFetch, { withRetry } from 'fetch-compose'
const fetch = withRetry(createFetch())
export default fetch
Individual Functions
./src/fetch.js
:
import { fetch, withJSON, withQuery, withThrowNonOk, withTimeout } from 'fetch-compose'
// Same as Default in README.md.
const fetch = withJSON(withQuery(withThrowNonOk(withTimeout(fetch))))
export default fetch
JWT Tokens
./src/fetch.js
:
import createFetch, { withJWTToken } from 'fetch-compose'
// Information for our login system.
const provider = {
baseHostname: 'dji.com',
getToken() {
return 'token'
},
async refreshToken() {
await doAsyncRefreshAction()
// We now have a new token! fetch-compose is able to retry the request.
}
}
const fetch = withJWTToken(createFetch(), provider)
export default fetch
Using FP compose function
./src/fetch.js
:
import compose from '@f/compose'
import { fetch, withJSON, withQuery, withThrowNonOk, withTimeout } from 'fetch-compose'
const fetch = compose(withJSON, withQuery, withThrowNonOk, withTimeout)(fetch)
export default fetch
License
Copyright 2020 DJI Technology LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
API
Table of Contents
Fetch
packages/fetch-compose/lib/types.ts:4-7
Generic type for WHATWG Fetch API.
Type: function (req: RequestInfo, opts: Partial<T>): Promise<Response>
withThrowNonOk
packages/fetch-compose/lib/withThrowNonOk.ts:6-17
Throws a generic Error if HTTP response is not "ok".
Parameters
fetch
Fetch<T>
Returns Fetch<T>
withQuery
packages/fetch-compose/lib/withQuery.ts:13-32
If Fetch options include an object 'query', this will be converted into the search params of the URL.
Parameters
fetch
Fetch<T>
Returns Fetch<any>
withJSON
packages/fetch-compose/lib/withJSON.ts:14-38
If Fetch options include a plain-object 'body', this will be converted into JSON with the Content-Type properly set to 'application/json' if not in 'headers'.
Parameters
fetch
Fetch<T>
Returns Fetch<any>
CredentialProvider
packages/fetch-compose/lib/withJWTToken.ts:15-31
Provider that is passed to 'withJWTToken'.
Type: {baseHostname: string, getToken: function (): Promise<string>, refreshToken: function (): Promise<void>}
Properties
baseHostname
packages/fetch-compose/lib/withJWTToken.ts:19-19
Base hostname for what credentials should be offered.
Type: string
getToken
packages/fetch-compose/lib/withJWTToken.ts:23-23
Gets the current JWT token.
Type: function (): Promise<string>
refreshToken
packages/fetch-compose/lib/withJWTToken.ts:30-30
Refresh the JWT token using the refresh token.
MUST throw an error on unsuccessful refresh for the higher-order function to work properly.
Type: function (): Promise<void>
withTimeout
packages/fetch-compose/lib/withTimeout.ts:33-63
Based on this: https://stackoverflow.com/questions/46946380/fetch-api-request-timeout/57888548#57888548
Will cancel request after timeout, with a default timeout of 10s.
Allows an optional field named 'timeout'.
Parameters
Returns Fetch<any>
createFetch
packages/fetch-compose/lib/index.ts:34-36
Creates an opinionated default for fetch.
- Automatically transforms a 'body' object into JSON request.
- Automatically appends a 'query' option into the search params of the request.
- Throws an error on non-2xx HTTP responses.
- Allows request to specify a timeout, with default of 10s.
Parameters
fetchVal
Fetch<RequestInit>?
withJWTToken
packages/fetch-compose/lib/withJWTToken.ts:48-128
Handles adding the bearer token for authorized routes, otherwise attempting to refresh the JWT token from backend.
Requires an implementation of {@type CredentialProvider}
Allows an optional field named 'skipRefresh'.
Parameters
fetch
Fetch<T>credentialProvider
CredentialProvider
Returns Fetch<any>