diff --git a/src/lib/localStorage.spec.ts b/src/lib/localStorage.spec.ts index 46db8de2..90484255 100644 --- a/src/lib/localStorage.spec.ts +++ b/src/lib/localStorage.spec.ts @@ -11,7 +11,7 @@ global.window = {} describe('localStorage', function() { const migrations: Migrations = { - 2: (data: any) => data + 2: (data: any) => ({ ...data, data: 'new version' }) } beforeEach(function() { @@ -43,6 +43,17 @@ describe('localStorage', function() { migrateStorage(key, migrations) data = JSON.parse(localStorage.getItem(key) as string) expect(data.storage.version).to.equal(2) + expect(data.data).to.equal('new version') + }) + + it('should set corrent version', function() { + const key = 'key' + const localStorage = getLocalStorage() + + localStorage.setItem(key, JSON.stringify('{ storage: { version: null }}')) + migrateStorage(key, migrations) + let data = JSON.parse(localStorage.getItem(key) as string) + expect(data.storage.version).to.equal(2) }) it('should not migrate if there is no migrations left', function() { @@ -54,6 +65,7 @@ describe('localStorage', function() { migrateStorage(key, migrations) data = JSON.parse(localStorage.getItem(key) as string) expect(data.storage.version).to.equal(2) + migrateStorage(key, migrations) expect(data.storage.version).to.equal(2) }) diff --git a/src/lib/localStorage.ts b/src/lib/localStorage.ts index 2c3a4f97..f4521d93 100644 --- a/src/lib/localStorage.ts +++ b/src/lib/localStorage.ts @@ -31,18 +31,21 @@ export function migrateStorage(key: string, migrations: Migrations) { if (dataString) { const data = JSON.parse(dataString as string) - if (data.storage) { - version = parseInt(data.storage.version || 0, 10) + if (data.storage && data.storage.version) { + version = parseInt(data.storage.version, 10) } + let nextVersion = version + 1 - version++ - while (migrations[version]) { - const newData = migrations[version](data) + while (migrations[nextVersion]) { + const newData = migrations[nextVersion](data) localStorage.setItem( key, - JSON.stringify({ ...(newData as Object), storage: { version } }) + JSON.stringify({ + ...(newData as Object), + storage: { version: nextVersion } + }) ) - version++ + nextVersion++ } } }