Skip to content

Commit

Permalink
Revert "Merge pull request Expensify#353 from margelo/@chrispader/rem…
Browse files Browse the repository at this point in the history
…ove-nested-nullish-object-keys"

This reverts commit 8671b9c, reversing
changes made to ce35c4e.
  • Loading branch information
ospfranco committed Sep 29, 2023
1 parent df715d8 commit f3a08f7
Show file tree
Hide file tree
Showing 7 changed files with 73 additions and 157 deletions.
14 changes: 9 additions & 5 deletions lib/Onyx.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {Component} from 'react';
import {PartialDeep} from 'type-fest';
import * as Logger from './Logger';
import {CollectionKey, CollectionKeyBase, DeepRecord, KeyValueMapping, NullishDeep, OnyxCollection, OnyxEntry, OnyxKey} from './types';
import {CollectionKey, CollectionKeyBase, DeepRecord, KeyValueMapping, OnyxCollection, OnyxEntry, OnyxKey, NullableProperties} from './types';

/**
* Represents a mapping object where each `OnyxKey` maps to either a value of its corresponding type in `KeyValueMapping` or `null`.
Expand Down Expand Up @@ -78,14 +79,14 @@ type OnyxUpdate =
| {
onyxMethod: typeof METHOD.MERGE;
key: TKey;
value: NullishDeep<KeyValueMapping[TKey]>;
value: PartialDeep<KeyValueMapping[TKey]>;
};
}[OnyxKey]
| {
[TKey in CollectionKeyBase]: {
onyxMethod: typeof METHOD.MERGE_COLLECTION;
key: TKey;
value: Record<`${TKey}${string}`, NullishDeep<KeyValueMapping[TKey]>>;
value: Record<`${TKey}${string}`, PartialDeep<KeyValueMapping[TKey]>>;
};
}[CollectionKeyBase];

Expand Down Expand Up @@ -201,7 +202,7 @@ declare function multiSet(data: Partial<NullableKeyValueMapping>): Promise<void>
* @param key ONYXKEYS key
* @param value Object or Array value to merge
*/
declare function merge<TKey extends OnyxKey>(key: TKey, value: NullishDeep<KeyValueMapping[TKey]>): Promise<void>;
declare function merge<TKey extends OnyxKey>(key: TKey, value: NullableProperties<PartialDeep<KeyValueMapping[TKey]>>): Promise<void>;

/**
* Clear out all the data in the store
Expand Down Expand Up @@ -243,7 +244,10 @@ declare function clear(keysToPreserve?: OnyxKey[]): Promise<void>;
* @param collectionKey e.g. `ONYXKEYS.COLLECTION.REPORT`
* @param collection Object collection keyed by individual collection member keys and values
*/
declare function mergeCollection<TKey extends CollectionKeyBase, TMap>(collectionKey: TKey, collection: Collection<TKey, TMap, NullishDeep<KeyValueMapping[TKey]>>): Promise<void>;
declare function mergeCollection<TKey extends CollectionKeyBase, TMap>(
collectionKey: TKey,
collection: Collection<TKey, TMap, PartialDeep<KeyValueMapping[TKey]>>,
): Promise<void>;

/**
* Insert API responses and lifecycle data into Onyx
Expand Down
27 changes: 9 additions & 18 deletions lib/Onyx.js
Original file line number Diff line number Diff line change
Expand Up @@ -1041,13 +1041,7 @@ function set(key, value) {
Logger.logAlert(`Onyx.set() called after Onyx.merge() for key: ${key}. It is recommended to use set() or merge() not both.`);
}

// We can remove all null values in an object by merging it with itself
// utils.fastMerge recursively goes through the object and removes all null values
// Passing two identical objects as source and target to fastMerge will not change it, but only remove the null values
let valueWithNullRemoved = value;
if (typeof value === 'object' && !_.isArray(value)) {
valueWithNullRemoved = utils.fastMerge(value, value);
}
const valueWithNullRemoved = utils.removeNullObjectValues(value);

const hasChanged = cache.hasValueChanged(key, valueWithNullRemoved);

Expand Down Expand Up @@ -1104,10 +1098,9 @@ function multiSet(data) {
* @private
* @param {*} existingValue
* @param {Array<*>} changes Array of changes that should be applied to the existing value
* @param {Boolean} shouldRemoveNullObjectValues
* @returns {*}
*/
function applyMerge(existingValue, changes, shouldRemoveNullObjectValues) {
function applyMerge(existingValue, changes) {
const lastChange = _.last(changes);

if (_.isArray(lastChange)) {
Expand All @@ -1116,7 +1109,7 @@ function applyMerge(existingValue, changes, shouldRemoveNullObjectValues) {

if (_.some(changes, _.isObject)) {
// Object values are then merged one after the other
return _.reduce(changes, (modifiedData, change) => utils.fastMerge(modifiedData, change, shouldRemoveNullObjectValues),
return _.reduce(changes, (modifiedData, change) => utils.fastMerge(modifiedData, change),
existingValue || {});
}

Expand Down Expand Up @@ -1164,8 +1157,7 @@ function merge(key, changes) {
.then((existingValue) => {
try {
// We first only merge the changes, so we can provide these to the native implementation (SQLite uses only delta changes in "JSON_PATCH" to merge)
// We don't want to remove null values from the "batchedChanges", because SQLite uses them to remove keys from storage natively.
let batchedChanges = applyMerge(undefined, mergeQueue[key], false);
let batchedChanges = applyMerge(undefined, mergeQueue[key]);

if (_.isNull(batchedChanges)) {
return remove(key);
Expand All @@ -1180,16 +1172,15 @@ function merge(key, changes) {
delete mergeQueuePromise[key];

// After that we merge the batched changes with the existing value
// We can remove null values from the "modifiedData", because "null" implicates that the user wants to remove a value from storage.
// The "modifiedData" will be directly "set" in storage instead of being merged
const modifiedData = shouldOverwriteExistingValue ? batchedChanges : applyMerge(existingValue, [batchedChanges], true);
const updatedValue = shouldOverwriteExistingValue ? batchedChanges : applyMerge(existingValue, [batchedChanges]);
const modifiedData = utils.removeNullObjectValues(updatedValue);

// On native platforms we use SQLite which utilises JSON_PATCH to merge changes.
// JSON_PATCH generally removes top-level nullish values from the stored object.
// When there is no existing value though, SQLite will just insert the changes as a new value and thus the null values won't be removed.
// Therefore we need to remove null values from the `batchedChanges` which are sent to the SQLite, if no existing value is present.
// When there is no existing value though, SQLite will just insert the changes as a new value and thus the top-level nullish values won't be removed.
// Therefore we need to remove nullish values from the `batchedChanges` which are sent to the SQLite, if no existing value is present.
if (!existingValue) {
batchedChanges = applyMerge(undefined, mergeQueue[key], true);
batchedChanges = utils.removeNullObjectValues(batchedChanges);
}

const hasChanged = cache.hasValueChanged(key, modifiedData);
Expand Down
2 changes: 1 addition & 1 deletion lib/storage/providers/IDBKeyVal.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const provider = {
const upsertMany = _.map(pairs, ([key, value], index) => {
const prev = values[index];
const newValue = _.isObject(prev) ? utils.fastMerge(prev, value) : value;
return promisifyRequest(store.put(newValue, key));
return promisifyRequest(store.put(utils.removeNullObjectValues(newValue), key));
});
return Promise.all(upsertMany);
});
Expand Down
57 changes: 19 additions & 38 deletions lib/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import {Merge} from 'type-fest';
import {BuiltIns} from 'type-fest/source/internal';

/**
* Represents a deeply nested record. It maps keys to values,
* and those values can either be of type `TValue` or further nested `DeepRecord` instances.
*/
type DeepRecord<TKey extends string | number | symbol, TValue> = {
[key: string]: TValue | DeepRecord<TKey, TValue>;
};
type DeepRecord<TKey extends string | number | symbol, TValue> = {[key: string]: TValue | DeepRecord<TKey, TValue>};

/**
* Represents type options to configure all Onyx methods.
Expand Down Expand Up @@ -183,42 +180,26 @@ type OnyxEntry<TOnyxValue> = TOnyxValue | null;
*/
type OnyxCollection<TOnyxValue> = OnyxEntry<Record<string, TOnyxValue | null>>;

type NonTransformableTypes =
| BuiltIns
| ((...args: any[]) => unknown)
| Map<unknown, unknown>
| Set<unknown>
| ReadonlyMap<unknown, unknown>
| ReadonlySet<unknown>
| unknown[]
| readonly unknown[];

/**
* Create a type from another type with all keys and nested keys set to optional or null.
*
* @example
* const settings: Settings = {
* textEditor: {
* fontSize: 14;
* fontColor: '#000000';
* fontWeight: 400;
* }
* autosave: true;
* };
* The `NullableProperties<T>` sets the values of all properties in `T` to be nullable (i.e., `| null`).
* It doesn't recurse into nested property values, this means it applies the nullability only to the top-level properties.
*
* const applySavedSettings = (savedSettings: NullishDeep<Settings>) => {
* return {...settings, ...savedSettings};
* }
*
* settings = applySavedSettings({textEditor: {fontWeight: 500, fontColor: null}});
* @template T The type of the properties to convert to nullable properties.
*/
type NullishDeep<T> = T extends NonTransformableTypes ? T : T extends object ? NullishObjectDeep<T> : unknown;

/**
Same as `NullishDeep`, but accepts only `object`s as inputs. Internal helper for `NullishDeep`.
*/
type NullishObjectDeep<ObjectType extends object> = {
[KeyType in keyof ObjectType]?: NullishDeep<ObjectType[KeyType]> | null;
type NullableProperties<T> = {
[P in keyof T]: T[P] | null;
};

export {CollectionKey, CollectionKeyBase, CustomTypeOptions, DeepRecord, Key, KeyValueMapping, OnyxCollection, OnyxEntry, OnyxKey, Selector, NullishDeep};
export {
CollectionKey,
CollectionKeyBase,
CustomTypeOptions,
DeepRecord,
Key,
KeyValueMapping,
OnyxCollection,
OnyxEntry,
OnyxKey,
Selector,
NullableProperties,
};
60 changes: 28 additions & 32 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import _ from 'underscore';
import * as _ from 'underscore';

function areObjectsEmpty(a, b) {
return (
Expand All @@ -25,26 +25,16 @@ function isMergeableObject(val) {
/**
* @param {Object} target
* @param {Object} source
* @param {Boolean} shouldRemoveNullObjectValues
* @returns {Object}
*/
function mergeObject(target, source, shouldRemoveNullObjectValues = true) {
const targetAndSourceIdentical = target === source;

function mergeObject(target, source) {
const destination = {};
if (isMergeableObject(target)) {
// lodash adds a small overhead so we don't use it here
// eslint-disable-next-line rulesdir/prefer-underscore-method
const targetKeys = Object.keys(target);
for (let i = 0; i < targetKeys.length; ++i) {
const key = targetKeys[i];

// If shouldRemoveNullObjectValues is true, we want to remove null values from the merged object
if (shouldRemoveNullObjectValues && (target[key] === null || source[key] === null)) {
// eslint-disable-next-line no-continue
continue;
}

destination[key] = target[key];
}
}
Expand All @@ -54,49 +44,55 @@ function mergeObject(target, source, shouldRemoveNullObjectValues = true) {
const sourceKeys = Object.keys(source);
for (let i = 0; i < sourceKeys.length; ++i) {
const key = sourceKeys[i];

// If shouldRemoveNullObjectValues is true, we want to remove null values from the merged object
if (shouldRemoveNullObjectValues && source[key] === null) {
if (source[key] === undefined) {
// eslint-disable-next-line no-continue
continue;
}

if (!isMergeableObject(source[key]) || !target[key]) {
if (targetAndSourceIdentical) {
// eslint-disable-next-line no-continue
continue;
}
destination[key] = source[key];
} else {
// eslint-disable-next-line no-use-before-define
destination[key] = fastMerge(target[key], source[key], shouldRemoveNullObjectValues);
destination[key] = fastMerge(target[key], source[key]);
}
}

return destination;
}

/**
* Merges two objects and removes null values if "shouldRemoveNullObjectValues" is set to true
*
* We generally want to remove null values from objects written to disk and cache, because it decreases the amount of data stored in memory and on disk.
* On native, when merging an existing value with new changes, SQLite will use JSON_PATCH, which removes top-level nullish values.
* To be consistent with the behaviour for merge, we'll also want to remove null values for "set" operations.
*
* @param {Object|Array} target
* @param {Object|Array} source
* @param {Boolean} shouldRemoveNullObjectValues
* @returns {Object|Array}
*/
function fastMerge(target, source, shouldRemoveNullObjectValues = true) {
function fastMerge(target, source) {
// We have to ignore arrays and nullish values here,
// otherwise "mergeObject" will throw an error,
// because it expects an object as "source"
if (_.isArray(source) || source === null || source === undefined) {
if (_.isArray(source) || _.isNull(source) || _.isUndefined(source)) {
return source;
}
return mergeObject(target, source, shouldRemoveNullObjectValues);
return mergeObject(target, source);
}

/**
* We generally want to remove top-level nullish values from objects written to disk and cache, because it decreases the amount of data stored in memory and on disk.
* On native, when merging an existing value with new changes, SQLite will use JSON_PATCH, which removes top-level nullish values.
* To be consistent with the behaviour for merge, we'll also want to remove nullish values for "set" operations.
* On web, IndexedDB will keep the top-level keys along with a null value and this uses up storage and memory.
* This method will ensure that keys for null values are removed before an object is written to disk and cache so that all platforms are storing the data in the same efficient way.
* @private
* @param {*} value
* @returns {*}
*/
function removeNullObjectValues(value) {
if (_.isArray(value) || !_.isObject(value)) {
return value;
}

const objectWithoutNullObjectValues = _.omit(value, objectValue => _.isNull(objectValue));

return objectWithoutNullObjectValues;
}

export default {areObjectsEmpty, fastMerge};
export default {removeNullObjectValues, areObjectsEmpty, fastMerge};

5 changes: 3 additions & 2 deletions tests/unit/onyxCacheTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -309,15 +309,16 @@ describe('Onyx', () => {
expect(cache.getValue('mockKey')).toEqual({value: 'myMockObject'});
});

it('Should merge a key with `undefined`', () => {
it('Should do nothing to a key which value is `undefined`', () => {
// Given cache with existing data
cache.set('mockKey', {ID: 5});

// When merge is called key value pair and the value is undefined
cache.merge({mockKey: undefined});

// Then the key should still be in cache and the value unchanged
expect(cache.getValue('mockKey')).toEqual(undefined);
expect(cache.hasCacheForKey('mockKey')).toBe(true);
expect(cache.getValue('mockKey')).toEqual({ID: 5});
});

it('Should update storageKeys when new keys are created', () => {
Expand Down
Loading

0 comments on commit f3a08f7

Please sign in to comment.