createMigrate.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { DEFAULT_VERSION } from './constants';
  2. export default function createMigrate(migrations, config) {
  3. var _ref = config || {},
  4. debug = _ref.debug;
  5. return function (state, currentVersion) {
  6. if (!state) {
  7. if (process.env.NODE_ENV !== 'production' && debug) console.log('redux-persist: no inbound state, skipping migration');
  8. return Promise.resolve(undefined);
  9. }
  10. var inboundVersion = state._persist && state._persist.version !== undefined ? state._persist.version : DEFAULT_VERSION;
  11. if (inboundVersion === currentVersion) {
  12. if (process.env.NODE_ENV !== 'production' && debug) console.log('redux-persist: versions match, noop migration');
  13. return Promise.resolve(state);
  14. }
  15. if (inboundVersion > currentVersion) {
  16. if (process.env.NODE_ENV !== 'production') console.error('redux-persist: downgrading version is not supported');
  17. return Promise.resolve(state);
  18. }
  19. var migrationKeys = Object.keys(migrations).map(function (ver) {
  20. return parseInt(ver);
  21. }).filter(function (key) {
  22. return currentVersion >= key && key > inboundVersion;
  23. }).sort(function (a, b) {
  24. return a - b;
  25. });
  26. if (process.env.NODE_ENV !== 'production' && debug) console.log('redux-persist: migrationKeys', migrationKeys);
  27. try {
  28. var migratedState = migrationKeys.reduce(function (state, versionKey) {
  29. if (process.env.NODE_ENV !== 'production' && debug) console.log('redux-persist: running migration for versionKey', versionKey);
  30. return migrations[versionKey](state);
  31. }, state);
  32. return Promise.resolve(migratedState);
  33. } catch (err) {
  34. return Promise.reject(err);
  35. }
  36. };
  37. }