All files / module/mutations updateMutation.js

0% Statements 0/32
0% Branches 0/16
0% Functions 0/7
0% Lines 0/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                     
import Vue from 'vue'
 
export function updateMutation (isCollection) {
  return new Proxy(() => {}, {
    apply (target, thisArg, [state, { id, path, value, relationship, action }]) {
      const rootSelector = (isCollection) ? 'items' : 'item'
 
      if (typeof relationship !== 'undefined') {
        path = `${rootSelector}.${id}.relationships.${relationship}.data`
        path = path.split('.')
 
        const selectedsList = path.reduce((obj, key) => obj[key], state)
        const prop = path.pop()
        if (value instanceof Array) {
          Vue.set(selectedsList, prop, value)
          return
        }
 
        if (!(value instanceof Array)) {
          if (action === 'remove') {
            const idx = selectedsList.findIndex(el => el.id === value.id)
            Vue.delete(selectedsList, idx)
          }
          if (action === 'add') {
            const length = selectedsList.length
            Vue.set(selectedsList, length, value)
          }
 
          // if its a 1-1 relation and we cant remove or add but only replace
          // we may find a more elegant way to handle that
          if (typeof action === 'undefined') {
            Vue.set(path.reduce((obj, key) => obj[key], state), prop, value)
          }
          return
        }
      }
 
      if (path.includes('attributes')) {
        path = `${rootSelector}.${id}.${path}`
        path = path.split('.')
        const prop = path.pop()
        const selectedsList = path.reduce((obj, key) => obj[key], state)
        Vue.set(selectedsList, prop, value)
        return
      }
 
      throw new Error('Update failed')
    }
  })
}