Skip to content

Commit

Permalink
fix: version and test
Browse files Browse the repository at this point in the history
BREAKING CHANGE: storage migrations
  • Loading branch information
nachomazzara committed Sep 17, 2018
1 parent 19f48a6 commit cf784e0
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
14 changes: 13 additions & 1 deletion src/lib/localStorage.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ global.window = {}

describe('localStorage', function() {
const migrations: Migrations<any> = {
2: (data: any) => data
2: (data: any) => ({ ...data, data: 'new version' })
}

beforeEach(function() {
Expand Down Expand Up @@ -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() {
Expand All @@ -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)
})
Expand Down
17 changes: 10 additions & 7 deletions src/lib/localStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,21 @@ export function migrateStorage<T>(key: string, migrations: Migrations<T>) {
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++
}
}
}

0 comments on commit cf784e0

Please sign in to comment.