bookshelf-manager icon indicating copy to clipboard operation
bookshelf-manager copied to clipboard

Add `patch` method

Open ericclemmons opened this issue 11 years ago • 0 comments

The patch method should operate like save, except it should pre-load and compute the optimal diff for saving:

var diff = function(before, after) {
  var patch = after;

  if (angular.isArray(after)) {
    patch = [];
  } else if (angular.isObject(after)) {
    patch = {};
  }

  if (angular.isObject(before) && angular.isDefined(after)) {
    // Compute difference for changed properties
    angular.forEach(before, function(left, key) {
      if (!angular.isDefined(after[key])) {
        return false;
      }

      var right = after[key];

      if (angular.isArray(after) || !angular.equals(left, right) || key === 'id') {
        patch[key] = diff(left, right);
      }
    });

    // Add new properties to patch
    angular.forEach(after, function(right, key) {
      if (!angular.isDefined(before[key])) {
        patch[key] = right;
      }
    });
  }

  return patch;
};

The save method should no longer pre-fetch a deep tree, and only patch should do that for calculation only, then defer to save for the actual saving.

ericclemmons avatar May 13 '14 16:05 ericclemmons