react-freezer-js
Version:
Mandatory context-based helpers for freezer-js and react.
56 lines (46 loc) • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.commit = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
exports.isFridge = isFridge;
exports.isObject = isObject;
exports.morph = morph;
var _freezerJs = require('freezer-js');
var _freezerJs2 = _interopRequireDefault(_freezerJs);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isFridge(fridge) {
return fridge instanceof _freezerJs2.default;
}
function isObject(value) {
// http://jsperf.com/isobject4
return value !== null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object';
}
// Applies a function to the current state to generate a delta and commits
// the delta (i.e. modifies the state) if it is not `undefined`.
// It handles promises as well.
function morph(fridge, fn) {
// inject the state and the commit function
fn.call(fridge, {
state: fridge.get(),
commit: function commit(delta) {
return _commit(fridge, delta);
}
});
}
// Apply the delta to the state (side-effect) and returns the delta,
// so that it can easily be tapped into a promise chain.
// check freezer-js documentation for more about update:
// @see https://github.com/arqex/freezer#update-methods
function _commit(fridge, delta) {
if (!isFridge(fridge)) {
throw new Error('commit() was applied on a non-freezer instance');
}
if (!isObject(delta)) {
throw new Error('delta should be an object');
}
fridge.get().set(delta);
return delta;
}
exports.commit = _commit;