Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import axios from 'axios'
- import { normalize } from 'normalizr'
- import { createActions } from 'redux-actions'
- const call = async (endpoint, options = {}, method = 'get', schema) => {
- try {
- const response = await axios({
- method,
- url: endpoint,
- headers: {'Content-Type': 'application/json'},
- ...options
- })
- return schema ? normalize(response.data, schema) : response.data
- } catch (error) {
- throw error
- }
- }
- // symbol for CALL_API
- export const CALL_API = Symbol('CALL_API')
- // actual middleware
- export default store => next => async action => {
- const callAPI = action[CALL_API]
- // so the middleware doesn't get applied to every single action
- if (typeof callAPI === 'undefined') {
- return next(action)
- }
- // get endpoint and types from action
- const { endpoint, types, options, method, schema } = callAPI
- // get API request types
- const [requestType, successType, failureType] = types
- // generate with meta field if there are extra params for the request
- const generateRequestActionPayload = (payloadCreator) => {
- if (typeof payloadCreator !== 'function') {
- throw new Error('payloadCreator should be a function')
- }
- if (typeof options === 'undefined') return payloadCreator
- return [
- payloadCreator,
- () => ({...options})
- ]
- }
- // create our request actions using the types provided
- const apiActions = createActions({
- [requestType]: generateRequestActionPayload(endpoint => ({endpoint})),
- [successType]: response => ({response}),
- [failureType]: [error => ({error}), error => ({message: error.message})]
- })
- // map the action names from our action map
- const [request, success, failure] = Object.keys(apiActions)
- // dispatch request action
- store.dispatch(apiActions[request](endpoint))
- return call(endpoint, options, method, schema).then(
- // if response dispatch success action
- response => next(apiActions[success](response)),
- // dispatch failure action on error
- error => next(apiActions[failure](error))
- )
- }
Add Comment
Please, Sign In to add comment