Skip to content

Commit

Permalink
now properly escaping key names prior to diffing objects (rancher#9865)
Browse files Browse the repository at this point in the history
  • Loading branch information
Sean-McQ authored Oct 6, 2023
1 parent 702c54e commit 86a448b
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 4 deletions.
68 changes: 67 additions & 1 deletion shell/utils/__tests__/object.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {
clone, get, getter, isEmpty, toDictionary, remove
clone, get, getter, isEmpty, toDictionary, remove, diff, definedKeys
} from '@shell/utils/object';

describe('fx: get', () => {
Expand Down Expand Up @@ -161,3 +161,69 @@ describe('fx: remove', () => {
expect(result).toStrictEqual(expected);
});
});

describe('fx: diff', () => {
it('should return an object including only the differences between two objects', () => {
const from = {
foo: 'bar',
baz: 'bang',
};
const to = {
foo: 'bar',
bang: 'baz'
};

const result = diff(from, to);
const expected = {
baz: null,
bang: 'baz'
};

expect(result).toStrictEqual(expected);
});
it('should return an object and dot characters in object should still be respected', () => {
const from = {};
const to = { foo: { 'bar.baz': 'bang' } };

const result = diff(from, to);
const expected = { foo: { 'bar.baz': 'bang' } };

expect(result).toStrictEqual(expected);
});
});

describe('fx: definedKeys', () => {
it('should return an array of keys within an array', () => {
const obj = {
foo: 'bar',
baz: 'bang',
};

const result = definedKeys(obj);
const expected = ['"foo"', '"baz"'];

expect(result).toStrictEqual(expected);
});
it('should return an array of keys with primitive values and their full nested path', () => {
const obj = {
foo: 'bar',
baz: { bang: 'bop' },
};

const result = definedKeys(obj);
const expected = ['"foo"', '"baz"."bang"'];

expect(result).toStrictEqual(expected);
});
it('should return an array of keys with primitive values and their full nested path with quotation marks to escape keys with dots in them', () => {
const obj = {
foo: 'bar',
baz: { 'bang.bop': 'beep' },
};

const result = definedKeys(obj);
const expected = ['"foo"', '"baz"."bang.bop"'];

expect(result).toStrictEqual(expected);
});
});
7 changes: 4 additions & 3 deletions shell/utils/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,12 @@ export function definedKeys(obj) {
const val = obj[key];

if ( Array.isArray(val) ) {
return key;
return `"${ key }"`;
} else if ( isObject(val) ) {
return ( definedKeys(val) || [] ).map((subkey) => `${ key }.${ subkey }`);
// no need for quotes around the subkey since the recursive call will fill that in via one of the other two statements in the if block
return ( definedKeys(val) || [] ).map((subkey) => `"${ key }".${ subkey }`);
} else {
return key;
return `"${ key }"`;
}
});

Expand Down

0 comments on commit 86a448b

Please sign in to comment.