0.2.0 • Published 7 years ago

disfetch v0.2.0

Weekly downloads
1
License
MIT
Repository
-
Last release
7 years ago

disfetch

Disfetch is a library for sending HTTP requests and dispatching Redux actions accordingly.

Purpose of this library

A common task in most Redux-based applications is sending requests to a server and dispatching actions based on the response. This library should simplify that and help you write less verbose code.

Example usage

You can use this in the same way as you would use the axios library.

// config always has the lowest priority when considering URL, method and data properties

disfetch('/') // the first parameter is always the URL, regardless of the method
disfetch('/', { method: 'get' }) // the default method

disfetch.request('/') // an alias to calling the disfetch instance directly
disfetch.request('/', { method: 'get' })

disfetch.get('/')
disfetch.get('/', { headers: { /* ... */ } }) // you can also use delete, head and options methods

disfetch.post('/')
disfetch.post('/', { id: 1 })
disfetch.post('/', { id: 1 }, { headers: { /* ... */ } }) // you can also use put and patch methods

The interesting stuff comes with using the with method.

disfetch.with(dispatch, 'APPROVE').get('/')

This will send a request to the specified URL ('/') and dispatch these actions:

// before sending the request

{
  type: 'APPROVE_REQUEST',
  payload: config, // parsed request fetch config (may not include axios default values)
  meta: {
    request: config // also the parsed request config (for convenience)
  }
}

// if the response is successful

{
  type: 'APPROVE_SUCCESS',
  payload: response.data,
  meta: {
    request, // request config (from response.request, made available by axios)
    response,
  }
}

// if the response is not successful

{
  type: 'APPROVE_FAILURE',
  payload: response.data || response.statusText || response.status || error.message,
  meta: {
    request, // request config (from response.request, made available by axios)
    response // may not be available
  }
}

You can also pass a configuration object instead of a string.

disfetch.with(dispatch, {
  requestAction: 'APPROVE_REQUEST', // mixed types are allowed
  successAction: {
    type: 'APPROVE_SUCCESS'
  },
  failureAction: (payload, { request, response }) => ({
    type: 'APPROVE_FAILURE',
    payload: payload,
    meta: {
      request,
      response
    }
  })
}).post('/', { value: 'waffle' }).then((response) => console.log(response))

This will send a POST request to the speciifed URL with the supplied JSON body.

An action of 'APPROVE_REQUEST' type will be dispatched before sending the request.

If it results in a successful response, the successAction is filled with response data and dispatched.

If it results in a failed response (or the request could not be sent at all), the failureAction function is called and the return value is dispatched.

Methods

// these methods return a promise resolved with the response object (see response schema)

disfetch( url [, fetchConfig ] )
disfetch.request( url [, fetchConfig ] )

disfetch.delete( url [, fetchConfig ] )
disfetch.get( url [, fetchConfig ] )
disfetch.head( url [, fetchConfig ] )
disfetch.options( url [, fetchConfig ] )

disfetch.patch( url [, data [, fetchConfig ] ] )
disfetch.post( url [, data [, fetchConfig ] ] )
disfetch.put( url [, data [, fetchConfig ] ] )

// these methods return a new disfetch instance with new configs set (merged recursively)

disfetch.create( [ dispatchConfig [, fetchConfig ] ] )
disfetch.with( [ dispatch, ] dispatchConfig )

// these methods return the original disfetch instance, its configs are RESET beforehand
// using these methods will mutate the instance, therefore their use is discouraged

disfetch.setDispatchConfig( [ dispatchConfig ] )
disfetch.setFetchConfig( [ fetchConfig ] )

Response schema

It is the unmodified axios response schema.

Dispatch configuration

It is merged with the default dispatch configuration of the instance (supplied one takes precedence). The object can be passed as an argument to the with or create method. Listed below are possible properties of the config. Defaults can also be found here.

dispatch

The dispatch function to dispatch the actions with. Can be passed as the first argument to the with method.

requestAction, successAction, failureAction

Actions to be dispatched before sending a request or after receiving a response (a successful one or a failed one).

  • It takes precedence over universalAction.
  • If it's a string, it is wrapped in an object, where the type property is the value. Then it behaves as if it were an object.
  • If it's an object, the payload and meta properties are set depending on the event:
    • Request event:
      • payload: request
      • meta: { request }
    • Success event:
      • payload: response.data
      • meta: { request, response }
    • Failure event:
      • payload: response.data || response.statusText || response.status || error.message
      • meta: { request, response }
  • If it's a function, it is called with payload and meta arguments (depending on the event). The return value is then dispatched.
  • If it's an array, every element is dispatched based on its type. This behaviour is recursive, arrays can be nested and of mixed types.
  • Note that if some edge use-case doesn't suit your needs, you can still use the transformResponse and transformRequest properties in the fetch config.
  • Any mix of types can be used.

universalAction

Default action for all events (request, success and failure). Event actions override the dispatch of this action (event actions take precedence, but if e.g. only one event action is specified, universal action is still dispatched for other events).

  • If it's a string, it is suffixed and handled like the corresponding event action (see e.g. requestAction).
  • If it's an object, it is dispatched like the corresponding event action. The action type is NOT suffixed.
  • If it's a function, it is called like the corresponding event action and the return value is dispatched afterwards.
  • If it's an array, every element is handled like the corresponding event action based on its type. This behaviour is recursive, arrays can be nested and of mixed types.
  • Objects and function calls won't be dispatched on request (can be overriden, see e.g. dispatchObjectOnRequest).

requestSuffix, successSuffix, failureSuffix

Suffixes to use for action types of corresponding events, default values are '_REQUEST', '_SUCCESS' and '_FAILURE'.

smartSuffixing

If universalAction is a string and ends with any of the suffixes, they are removed and replaced with the correct one. The default value is true (this behaviour is enabled).

dispatchObjectOnRequest, dispatchFunctionCallOnRequest

If universalAction is an object, it will also be dispatched on request event. If it's a function, it is called and the return value will also be dispatched on request event. The default value is false. If you pass an object or a function to universalAction, the default behaviour is to dispatch it only after the request is fully handled (as finally would).

args

Array of arguments to call the functions with (appended to the end, an alternative to fn.bind). The default value is an empty array. You can also provide a single non-array value. Note that the first two default arguments (payload, meta) ARE preserved.

Fetch configuration

It is merged with the default config of the instance (supplied one takes precedence). Passing it to any of the request methods will NOT mutate the instance or create a new one – the config will be used just for the request. Listed below are possible properties of the config.

jwt

Will add an 'Authorization: Bearer ' + jwt header if an encoded JSON Web Token string is supplied.

The rest is passed straight to axios. See the axios request config.