[fix] AsyncStorage.mergeItem to support deep merge

Mirrors behaviour of react-native
This commit is contained in:
Xiaohan Zhang
2016-10-13 10:27:51 -07:00
committed by Nicolas Gallagher
parent dbd607ce47
commit ee7d367062
2 changed files with 63 additions and 2 deletions

View File

@@ -1,5 +1,65 @@
/* eslint-env mocha */
import assert from 'assert';
import AsyncStorage from '..';
const waterfall = (fns, cb) => {
const _waterfall = (...args) => {
const fn = (fns || []).shift();
if (typeof fn === 'function') {
fn(...args, (err, ...nextArgs) => {
if (err) {
return cb(err);
} else {
return _waterfall(...nextArgs);
}
});
} else {
cb(null, ...args);
}
};
_waterfall();
};
suite('apis/AsyncStorage', () => {
test.skip('NO TEST COVERAGE', () => {});
suite('mergeLocalStorageItem', () => {
test('should have same behavior as react-native', (done) => {
// https://facebook.github.io/react-native/docs/asyncstorage.html
const UID123_object = {
name: 'Chris',
age: 30,
traits: { hair: 'brown', eyes: 'brown' }
};
const UID123_delta = {
age: 31,
traits: { eyes: 'blue', shoe_size: 10 }
};
waterfall([
(cb) => {
AsyncStorage.setItem('UID123', JSON.stringify(UID123_object))
.then(() => cb(null))
.catch(cb);
},
(cb) => {
AsyncStorage.mergeItem('UID123', JSON.stringify(UID123_delta))
.then(() => cb(null))
.catch(cb);
},
(cb) => {
AsyncStorage.getItem('UID123')
.then((result) => {
cb(null, JSON.parse(result));
})
.catch(cb);
}
], (err, result) => {
assert.equal(err, null);
assert.deepEqual(result, {
'name': 'Chris', 'age': 31, 'traits': {
'shoe_size': 10, 'hair': 'brown', 'eyes': 'blue'
}
});
done();
});
});
});
});

View File

@@ -3,12 +3,13 @@
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*/
import merge from 'lodash/merge';
const mergeLocalStorageItem = (key, value) => {
const oldValue = window.localStorage.getItem(key);
const oldObject = JSON.parse(oldValue);
const newObject = JSON.parse(value);
const nextValue = JSON.stringify({ ...oldObject, ...newObject });
const nextValue = JSON.stringify(merge({}, oldObject, newObject));
window.localStorage.setItem(key, nextValue);
};