Because the process of manipulating data before requests and after responses is a little fiddly, the library provides a basic plugin architecture to make it easier.
Plugins wrap up request and response data modification into easy-to-use functions that can be called directly, or added by name to all Api classes.
There are currently three supplied plugins:
data
- convenience function to return thedata
component only from any callsremap
- remaps key names from client to server and back againresource
- converts outgoing and incoming data to and from models
To use plugins, use the use()
method of any of the Api classes:
const endpoint = new ApiEndpoint(axios, config)
.use('resource', Post)
.use('remap', { the_title: 'title'}, the_body: 'body')
.use('data')
Plugins are just a function which receives an Api instance as its first argument, then any additional parameters passed:
function doSomething (api, foo, bar) { ... }
To extend the uppercase example from the hooks page, we might do the following:
import { helpers } from 'axios-actions'
// create plugin
function changeCase (api, state) {
const transform = state ? 'toUpperCase': 'toLowerCase'
const onResponse = function (res) {
helpers.process(res.data => item => {
Object
.keys(item)
.forEach(key => {
item[key] = String(item)[transform]()
})
})
}
api.http.after.push(res => onResponse)
}
To implement it in our project, we can do either of the following:
// add to global plugins
import { plugins } from 'axios-actions'
plugins.changeCase = changeCase
// implement via use()
const posts = new ApiEndpoint('posts/:id')
.use('changeCase', true)
// implement via calling
changeCase(posts, false)
You can do anything you like with the api
instance in the plugin, for example adding callbacks:
plugins.log = function (api) {
api.fail(error => {
console.log('ERROR!', error)
return Promise.reject(error)
})
}
- Docs: Helpers
- Code:
src/classes/functions/plugins.ts