change-spotting
v1.1.0
Published
Create a changes object for two other objects that is consistent with a Rails update request
Downloads
12
Readme
change-spotting
Function for producing an update object that describes the differences between two values. that contains the differences in a format consistent with Rails update requests
Usage
import changes from 'change-spotting';
const updateObject = changes(original, changed, { alwaysInclude: ['id'] });
change-spotting
exports a single function for creating a Rails update object. It accepts 3 parameters:
- original: the original, unchanged object
- changed: the new or changed object
- options:
- alwaysInclude: an array of attribute names that should always be included in the change object, whether they have changed or not. Useful for listing primary identifiers Rails needs to find the resource in order to update it.
Examples
import changes from 'change-spotting';
const original = {
a: 'a',
b: 'b',
c: [1,2,3],
i: [4,5,6],
d: {
e: 'e',
f: 'f',
h: 'h'
},
g: [
{ id: 1, h: 'h1', j: 'j1' },
{ id: 2, h: 'h2', j: 'j2' },
{ id: 3, h: 'h3', j: 'j3' }
]
};
const changed = {
// changed value
a: 'a2',
// unchanged value
b: 'b',
// elements added to flat array
c: [1,2,3,4],
// elements removed from flat array
i: [4,5,6],
d: {
// unchanged nested attribute
e: 'e',
// changed nested attributes
f: 'f2'
// removed object attribute
},
g: [
// changed object in array
{ id: 1, h: 'h12', j: 'j1' },
// removed object from array
// unchanged object in array
{ id: 3, h: 'h3', j: 'j3' },
// new object with an identifier added to array
{ id: 4, h: 'h4', j: 'j4' },
// new object without an identifier added to array
{ h: 'h5' }
]
};
const updateObject = changes(original, changed, { alwaysInclude: ['id'] });
updateObject === {
// changed value
a: 'a2',
// unchanged value
// elements added to flat array
c: [1,2,3,4],
// elements removed from flat array
i: [4,5,6],
d: {
// unchanged nested attribute
// changed nested attributes
f: 'f2'
// removed object attribute
},
g: {
// changed object in array
0: { id: 1, h: 'h12' },
// removed object from array
1: { id: 2, '_destroy': true },
// unchanged object in array
// new object with an identifier added to array
2: { id: 4, h: 'h4', j: 'j4' },
// new object without an identifier added to array
3: { h: 'h5' }
}
};
Running the test suite
npm run tests