Guest User

Untitled

a guest
Feb 20th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. import axios from 'axios'
  2. import { normalize } from 'normalizr'
  3. import { createActions } from 'redux-actions'
  4.  
  5. const call = async (endpoint, options = {}, method = 'get', schema) => {
  6. try {
  7. const response = await axios({
  8. method,
  9. url: endpoint,
  10. headers: {'Content-Type': 'application/json'},
  11. ...options
  12. })
  13. return schema ? normalize(response.data, schema) : response.data
  14. } catch (error) {
  15. throw error
  16. }
  17. }
  18.  
  19. // symbol for CALL_API
  20. export const CALL_API = Symbol('CALL_API')
  21.  
  22. // actual middleware
  23. export default store => next => async action => {
  24. const callAPI = action[CALL_API]
  25. // so the middleware doesn't get applied to every single action
  26. if (typeof callAPI === 'undefined') {
  27. return next(action)
  28. }
  29.  
  30. // get endpoint and types from action
  31. const { endpoint, types, options, method, schema } = callAPI
  32.  
  33. // get API request types
  34. const [requestType, successType, failureType] = types
  35.  
  36. // generate with meta field if there are extra params for the request
  37. const generateRequestActionPayload = (payloadCreator) => {
  38. if (typeof payloadCreator !== 'function') {
  39. throw new Error('payloadCreator should be a function')
  40. }
  41. if (typeof options === 'undefined') return payloadCreator
  42. return [
  43. payloadCreator,
  44. () => ({...options})
  45. ]
  46. }
  47.  
  48. // create our request actions using the types provided
  49. const apiActions = createActions({
  50. [requestType]: generateRequestActionPayload(endpoint => ({endpoint})),
  51. [successType]: response => ({response}),
  52. [failureType]: [error => ({error}), error => ({message: error.message})]
  53. })
  54.  
  55. // map the action names from our action map
  56. const [request, success, failure] = Object.keys(apiActions)
  57.  
  58. // dispatch request action
  59. store.dispatch(apiActions[request](endpoint))
  60.  
  61. return call(endpoint, options, method, schema).then(
  62. // if response dispatch success action
  63. response => next(apiActions[success](response)),
  64. // dispatch failure action on error
  65. error => next(apiActions[failure](error))
  66. )
  67. }
Add Comment
Please, Sign In to add comment