All files / src/model ModelActions.js

86.49% Statements 64/74
64.29% Branches 9/14
86.11% Functions 31/36
87.5% Lines 63/72
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154              9x 9x 9x 9x 9x       8x 8x 8x 8x 8x 12x 8x         8x                               8x 8x 8x         16x       4x   4x 2x   2x   4x   4x 4x   4x 4x         1x 1x 1x 1x         1x 1x   1x 1x         1x 1x   1x 1x 1x       1x 1x 1x 1x 1x         1x 1x 1x 1x         1x 1x 1x 1x 1x         1x 1x 1x 1x 1x         1x 1x 1x 1x 1x                                  
import _ from 'lodash'
import { schema, normalize } from 'normalizr';
import { REQUEST, RESPONSE, ACTION, ERROR, SELECTED, RECEIVED, CLEAR } from '../constants'
 
//TODO: Move URL related logic to APIAdapter
export default class ModelActions {
  constructor(model, config, routeParams = {}, api, requestAdapter) {
    this.model = model
    this.entitySchema = new schema.Entity(model.modelName)
    this.routeParams = routeParams
    this.api = api
    this.requestAdapter = requestAdapter
  }
 
  _successHandler(dispatch, creator) {
    return (response) => {
      console.log('request succeeded with JSON response', response)
      const actionResult = creator(response)
      const actions = _.isArray(actionResult) ? actionResult : [actionResult]
      console.log('firing actions:', actions)
      actions.forEach(action => dispatch(action))
      return response
    }
  }
 
  _errorHandler(dispatch) {
    return (error) => {
      console.log('request failed', error)
      const dispatchError = (error, message) => dispatch({ type: ERROR, payload: { modelName: this.model.modelName, error, message } })
      if (error.response) {
        error.response.json().then((response) => {
          dispatchError(response.error, error.message)
        })
      } else {
        dispatchError(error, error.message)
      }
      throw error
      //return error
    }
  }
 
  _call(path, method, fetchOptions, requestCreator, successCreator) {
    return dispatch => {
      dispatch(requestCreator())
      return this.api.fetch(path, method, fetchOptions, this._successHandler(dispatch, successCreator), this._errorHandler(dispatch))
    }
  }
 
  _createAction(type, others) {
    return { type, payload: { ...others, modelName: this.model.modelName } }
  }
 
  _createNormalized(type, singleInstance = false, listName = undefined) {
    return (response) => {
      let normalized
      if (_.isArray(response)) {
        normalized = normalize(response, [this.entitySchema])
      } else {
        normalized = normalize(response, this.entitySchema)
      }
      console.log('normalized: ', normalized)
 
      const actions = _.map(normalized.entities, (entities, modelName) => {
        return { type: RECEIVED, payload: { modelName, instances: entities } }
      })
      actions.push(this._createAction(type, { [singleInstance ? 'id' : 'ids']: normalized.result, listName }))
      return actions;
    }
  }
  
  create(data) {
    const apiPath = this.requestAdapter.resolveRouteParams(this.model, this.routeParams)
    const {url, method, options} = this.requestAdapter.create(data, {apiPath})
    return this._call(url, method, options,
      () => this._createAction(REQUEST.CREATE, { data }),
      this._createNormalized(RESPONSE.CREATE, true))
  }
 
  update(id, data) {
    const apiPath = this.requestAdapter.resolveRouteParams(this.model, this.routeParams)
    const {url, method, options} = this.requestAdapter.update(id, data, {apiPath})
 
    return this._call(url, method, options,
      () => this._createAction(REQUEST.UPDATE, { id, data }),
      this._createNormalized(RESPONSE.UPDATE, true))
  }
 
  updateAll(where, data) {
    const apiPath = this.requestAdapter.resolveRouteParams(this.model, this.routeParams)
    const {url, method, options} = this.requestAdapter.updateAll(where, data, {apiPath})
 
    return this._call(url, method, options,
      () => this._createAction(REQUEST.UPDATE_ALL, { where, data }),
      (response) => this._createAction(RESPONSE.UPDATE_ALL, { count: response.count }))
  }
 
  find(filter, listName = undefined) {
    const apiPath = this.requestAdapter.resolveRouteParams(this.model, this.routeParams)
    console.log('using apiPath', apiPath)
    const {url, method, options} = this.requestAdapter.find(filter, {apiPath})
    return this._call(url, method, options,
      () => this._createAction(REQUEST.FIND, { filter, listName }),
      this._createNormalized(RESPONSE.FIND, false, listName))
  }
 
  findById(id, filter) {
    const apiPath = this.requestAdapter.resolveRouteParams(this.model, this.routeParams)
    const {url, method, options} = this.requestAdapter.findById(id, filter, {apiPath})
    return this._call(url, method, options,
      () => this._createAction(REQUEST.FIND_BY_ID, { id, filter }),
      this._createNormalized(RESPONSE.FIND_BY_ID, true))
  }
 
  deleteById(id) {
    const apiPath = this.requestAdapter.resolveRouteParams(this.model, this.routeParams)
    const {url, method, options} = this.requestAdapter.deleteById(id, {apiPath})
    return this._call(url, method, options,
      () => this._createAction(REQUEST.DELETE_BY_ID, { id }),
      (response) => this._createAction(RESPONSE.DELETE_BY_ID, { id: id })
    )
  }
 
  count(where, listName=null) {
    const apiPath = this.requestAdapter.resolveRouteParams(this.model, this.routeParams)
    const {url, method, options} = this.requestAdapter.count(where, {apiPath})
    return this._call(url, method, options,
      () => this._createAction(REQUEST.COUNT, { where, listName }),
      (response) => this._createAction(RESPONSE.COUNT, { count: response.count, listName })
    )
  }
 
  custom(name, path, _method, _options = {}) {
    const apiPath = this.requestAdapter.resolveRouteParams(this.model, this.routeParams)
    const {url, method, options} = this.requestAdapter.custom(name, path, _method, _options, {apiPath})
    return this._call(url, method, options,
      () => this._createAction(REQUEST.CUSTOM, { name, path, _method, _options }),
      (response) => this._createAction(RESPONSE.CUSTOM, { response: response, name })
    )
  }
 
  clear() {
    return this._createAction(CLEAR, { })
  }
 
  delete(filter) {
    throw new Error('not implemented yet')
    // return this._delete(`${this.apiPath}`, {filter: JSON.stringify(filter)},
    //   () => this._createAction(REQUEST.DELETE, { filter }),
    //   (response) => _createPayload(RESPONSE.DELETE, { ids: response.ids })
    // )
  }
 
}