From ee7d3670626229f4d4c07bc730ab27f675faf394 Mon Sep 17 00:00:00 2001 From: Xiaohan Zhang Date: Thu, 13 Oct 2016 10:27:51 -0700 Subject: [PATCH] [fix] AsyncStorage.mergeItem to support deep merge Mirrors behaviour of react-native --- src/apis/AsyncStorage/__tests__/index-test.js | 62 ++++++++++++++++++- src/apis/AsyncStorage/index.js | 3 +- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/src/apis/AsyncStorage/__tests__/index-test.js b/src/apis/AsyncStorage/__tests__/index-test.js index 826bd7e1..7ea5b627 100644 --- a/src/apis/AsyncStorage/__tests__/index-test.js +++ b/src/apis/AsyncStorage/__tests__/index-test.js @@ -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(); + }); + }); + }); }); diff --git a/src/apis/AsyncStorage/index.js b/src/apis/AsyncStorage/index.js index d5a15775..227c9e80 100644 --- a/src/apis/AsyncStorage/index.js +++ b/src/apis/AsyncStorage/index.js @@ -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); };