data-commander
v0.3.0
Published
Migrate data from schema.
Downloads
8
Readme
data-commander
Migrate data from schema.
Installation
yarn add data-commander
Usage
Migrate
import { Commander, SetCommand, DeleteCommand } from 'data-commander';
const data = {
x: 1,
y: 2,
};
const commander = new Commander([
new SetCommand(['x'], 10),
new DeleteCommand(['y']),
]);
commander.execute(data);
console.log(data); // { x: 10 }
Create Schema
const data = {
x: 1,
y: 2,
};
const commander = new Commander([
new SetCommand(['x'], 10),
new DeleteCommand(['y']),
]);
const schema = commander.execute({});
// {
// up: [
// { type: 'set', path: ['x'], data: 10 },
// { type: 'delete', path: ['y'], data: null }
// ],
// down: [
// {type: 'set', path: ['y'], data: 2 },
// { type: 'set', path: ['x'], data: 1 }
// ],
// id: 'c5rgDxMM_pML9079'
// }
Migrate or Revert
const data = {
x: 1,
y: 2,
};
const commander = new Commander([
new SetCommand(['x'], 10),
new DeleteCommand(['y']),
]);
const schema = commander.execute(data);
console.log(data); // { x: 10 }
Commander.fromSchema(schema).revert(data);
console.log(data); // { x: 1, y: 2 }
Commander.fromSchema(schema).migrate(data);
console.log(data); // { x: 10 }
Commands
SetCommand
Set a value to specific path.
const data = {};
const commander = new Commander([
new SetCommand(['test'], { hello: 'world' })
]);
commander.execute(data);
console.log(data); // { test: { hello: 'world' } }
DeleteCommand
Delete a specific object property or array item.
const data = { a: 1, b: 2 };
const commander = new Commander([
new DeleteCommand(['a'])
]);
commander.execute(data);
console.log(data); // { b: 2 }
InsertCommand
Insert an item to array with specific index.
const data = ['a', 'b'];
const commander = new Commander([
new InsertCommand(['1'], 'c')
]);
commander.execute(data);
console.log(data); // ['a', 'c', 'b']
commander.execute(data);
console.log(data); // ['a', 'c', 'c', 'b']
LpushCommand
Left push an item to array.
const data = ['a', 'b'];
const commander = new Commander([
new LpushCommand([], 'c')
]);
commander.execute(data);
console.log(data); // ['c', 'a', 'b']
commander.execute(data);
console.log(data); // ['c', 'c', 'a', 'b']
RpushCommand
Right push an item to array.
const data = ['a', 'b'];
const commander = new Commander([
new RpushCommand([], 'c')
]);
commander.execute(data);
console.log(data); // ['a', 'b', 'c']
commander.execute(data);
console.log(data); // ['a', 'b', 'c', 'c']
MergeCommand
Merge deep object to another object.
const data = {
x: {
y: 1,
z: 3,
},
};
const commander = new Commander([
new MergeCommand({
x: {
y: 2,
m: {
n: 4,
},
},
}),
]);
commander.execute(data);
console.log(data);
// {
// x: {
// y: 2,
// z: 3,
// m: {
// n: 4
// }
// }
// }
OR merge an array item.
const data = ['a', 'b'];
const commander = new Commander([
new MergeCommand(['4': 'c']),
]);
commander.execute(data);
console.log(data); // [ 'a', 'b', <empty>, <empty>, 'c' ]