react-native-onyx
Version:
State management for React Native
38 lines (37 loc) • 2.3 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const OnyxUtils_1 = __importDefault(require("../OnyxUtils"));
const OnyxCache_1 = __importDefault(require("../OnyxCache"));
const storage_1 = __importDefault(require("../storage"));
const applyMerge = (key, existingValue, validChanges) => {
// If any of the changes is null, we need to discard the existing value.
const baseValue = validChanges.includes(null) ? undefined : existingValue;
// We first batch the changes into a single change with object removal marks,
// so that SQLite can merge the changes more efficiently.
const { result: batchedChanges, replaceNullPatches } = OnyxUtils_1.default.mergeAndMarkChanges(validChanges);
// We then merge the batched changes with the existing value, because we need to final merged value to broadcast to subscribers.
const { result: mergedValue } = OnyxUtils_1.default.mergeChanges([batchedChanges], baseValue);
// In cache, we don't want to remove the key if it's null to improve performance and speed up the next merge.
const hasChanged = OnyxCache_1.default.hasValueChanged(key, mergedValue);
// Logging properties only since values could be sensitive things we don't want to log.
OnyxUtils_1.default.logKeyChanged(OnyxUtils_1.default.METHOD.MERGE, key, mergedValue, hasChanged);
// This approach prioritizes fast UI changes without waiting for data to be stored in device storage.
const updatePromise = OnyxUtils_1.default.broadcastUpdate(key, mergedValue, hasChanged);
// If the value has not changed, calling Storage.setItem() would be redundant and a waste of performance, so return early instead.
if (!hasChanged) {
return Promise.resolve({ mergedValue, updatePromise });
}
// For native platforms we use `mergeItem` that will take advantage of JSON_PATCH and JSON_REPLACE SQL operations to
// merge the object in a performant way.
return storage_1.default.mergeItem(key, batchedChanges, replaceNullPatches).then(() => ({
mergedValue,
updatePromise,
}));
};
const OnyxMerge = {
applyMerge,
};
exports.default = OnyxMerge;
;