Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including pojo-migrator with all npm packages installed. Try it out:

var pojoMigrator = require("pojo-migrator")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

pojo-migrator v2.1.0

A utility for migrating simple javascript object formats

Pojo Migrator Build Status

npm install pojo-migrator -S

A simple utility for migrating data stored in a a simple pojo (Plan Ol' Javascript Object).

Originally built for storing configuration values in the localStorage API, but could work with any synchronous object serialization protocol.

This module is entirely synchronous right now, because localStorage is, but could be easily modified to suit different needs.

var Migrator = require('..')

// In this example, our existing data looks like this.
var persistedData = {

  // Note the mandatory and reserved `meta` key,
  // with a mandatory `version` number.
  meta: {
    version: 1
  },

  // All your data is held in your own structure
  // Under the root `data` key.
  data: {
    foo: 'bar'
  }
}

var migrator = new Migrator({

  // Must provide a method to load existing data.
  // Defaults to empty object ({})
  loadData: function() {
    return persistedData
  },

  // Must provide a method to persist updated data
  setData: function(data) {
    persistedData = data
  },

  migrations: [

    // Each `migrate` function will be run in order.
    // It will be passed the contents of the `data` key.
    // The `meta` object and version will be updated automatically.
    {
      version: 1,
      migrate: function(data) {
        return data.config // Will error if run
      }
    },
    {
      version: 2,
      migrate: function(data) {
        var result = {}
        if (data.foo) {
          result.foos = [data.foo]
        }
        return result
      }
    },

    // Migrations do not need to be in order
    // As long as their version keys are ordered.
    {
      version: 0,
      migrate: function(data) {
        var result = {}
        if (data.foo) {
          result.foo = data
        }
        return result
      }
    }
  ]
})

// The result of `getData` is just your `data` key.
// You can pretty much ignore the versioning once you're set up!
var result = migrator.getData()

// After making changes, be sure to tell your migrator to `saveData`.
// This will automatically persist with the method you've defined in your
// `setData` method, but keeping the `meta` key up to date with the version.
result.foos.push('baz')
migrator.saveData(result)
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free