createMigrate.js.flow 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // @flow
  2. import { DEFAULT_VERSION } from './constants'
  3. import type { PersistedState, MigrationManifest } from './types'
  4. export default function createMigrate(
  5. migrations: MigrationManifest,
  6. config?: { debug: boolean }
  7. ) {
  8. let { debug } = config || {}
  9. return function(
  10. state: PersistedState,
  11. currentVersion: number
  12. ): Promise<PersistedState> {
  13. if (!state) {
  14. if (process.env.NODE_ENV !== 'production' && debug)
  15. console.log('redux-persist: no inbound state, skipping migration')
  16. return Promise.resolve(undefined)
  17. }
  18. let inboundVersion: number =
  19. state._persist && state._persist.version !== undefined
  20. ? state._persist.version
  21. : DEFAULT_VERSION
  22. if (inboundVersion === currentVersion) {
  23. if (process.env.NODE_ENV !== 'production' && debug)
  24. console.log('redux-persist: versions match, noop migration')
  25. return Promise.resolve(state)
  26. }
  27. if (inboundVersion > currentVersion) {
  28. if (process.env.NODE_ENV !== 'production')
  29. console.error('redux-persist: downgrading version is not supported')
  30. return Promise.resolve(state)
  31. }
  32. let migrationKeys = Object.keys(migrations)
  33. .map(ver => parseInt(ver))
  34. .filter(key => currentVersion >= key && key > inboundVersion)
  35. .sort((a, b) => a - b)
  36. if (process.env.NODE_ENV !== 'production' && debug)
  37. console.log('redux-persist: migrationKeys', migrationKeys)
  38. try {
  39. let migratedState = migrationKeys.reduce((state, versionKey) => {
  40. if (process.env.NODE_ENV !== 'production' && debug)
  41. console.log(
  42. 'redux-persist: running migration for versionKey',
  43. versionKey
  44. )
  45. return migrations[versionKey](state)
  46. }, state)
  47. return Promise.resolve(migratedState)
  48. } catch (err) {
  49. return Promise.reject(err)
  50. }
  51. }
  52. }