response-callbacks
Manually dealing with responses can be tedious and memorizing what every code means isnt something i enjoy doing. So I put together a list of common callbacks that can be used with the response object.
Install
npm install --save response-callbacks
Example Usage
response-callbacks takes in two parameters. Response and an object containing methods you want called back to.
import RepsonseCallbacks from 'response-callbacks'
let callBacks = {
success: (response) => { console.log('success', response) },
validation: (response) => { console.log('form validation errors', response.json()) },
server_error: (response) => { console.log('server error', response.status) },
420: (response) => { console.log('Enhance Your Calm') }
}
let request = fetch('/endpoint').then((response) => {
return (new ResponseCallbacks(response, callBacks)).run()
})
request.catch(function (err) { console.error('error', err.message) })
Callback Methods
I put together a list of most used methods. Optionally you can just have the actual status code in your object and it will be called as well.
200's
success: 2**
ok: 200
created: 201
no_content: 204
300's
redirection: 3**
moved_permanently: 301
not_modified: 304
400's
client_error: 4**
bad_request: 400
unauthorized: 401
forbidden: 403
not_found: 404
conflict: 409
unprocessable_entity: 422
validation: 422
500's
server_error: 5**
internal_server_error: 500
bad_gateway: 502
service_unavailable: 503
gateway_timeout: 504