js-fetch-api
v1.3.5
Published
JS Fetch api
Downloads
4
Readme
fetch api
This package is a fetch utility for React
Install
npm i fetch-api
Why using this instead of fetch ?
- Failure errors return as JSON with status, headers, response, stackTrace, message, etc.
- Uses redux thunk to dispatch events with request/success/failure action types
- Error action dispatch:
- 3xx: API/CALL/REDIRECT
- over 4xx: API/CALL/REJECTED
- 401: SERVER/UNAUTHORIZED/ERROR
- over 500: SERVER/INTERNAL/ERROR
- Uses mocked calls in dev environment
- Simulates expected error rate, as in 50% of this calls return a 404, etc.
- Simulate answer delay
- Define expected payloads for mocked calls.
- Adds NAV_CSRF_PROTECTION cookie, ts param to overcome browsers that cache AJAX results
Can you give me an example
In your actions folder, you can have something like this:
import { ActionWithPayload, call, ThunkResult } from 'js-fetch-api'
export const getPersonInfo: ActionCreator<ThunkResult<ActionWithPayload<PersonPDL>>> = (
id: string
): ThunkResult<ActionWithPayload<PersonPDL>> => {
return call({
url: '/api/person/' + id,
expectedPayload: {
personname: 'Demo Demo',
username: 'demo'
},
expectedErrorRate: {
200 : 0.8, 401: 0.1, 500: 0.1
},
maxDelayTime: 2000,
responseType: 'json',
cascadeFailureError: true,
type: {
request: 'PERSONINFO/REQUEST',
success: 'PERSONINFO/SUCCESS',
failure: 'PERSONINFO/FAILURE'
}
})
}
What does this do?
- In production environment, it will call the URL endpoint and return the result as JSON (responseType can also be 'pdf' or 'blob')
- will dispatch a request action, then a success or failure action
- If cascadeFailureError is false, in case of 500 errors, it will not dispatch failure action. IF cascade is true, it will dispatch failure action, in addition to SERVER/INTERNAL/ERROR
- expectedErrorRate: {200 : 0.8, 401: 0.1, 500: 0.1} means that, in dev environment (NOT in production), there is:
- 80% chance for a 200 answer
- 10% chance for a 401 answer
- 10% chance for a 500 answer This is great to simulate backend errors / failures