Skip to content

Commit

Permalink
Properly serialize getKeyErrorValues with nested
Browse files Browse the repository at this point in the history
  • Loading branch information
snewcomer committed Mar 25, 2020
1 parent 23f65ac commit ce85db1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 13 deletions.
18 changes: 6 additions & 12 deletions src/utils/get-key-values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,40 +27,34 @@ export function getKeyValues<T extends Record<string, any>>(
return map;
}

let errorKeysUpToValue: string[] = [];

/**
* traverse through target and return leaf nodes with `value` property and key as 'person.name'
*
* @method getKeyErrorValues
* @return {Array} [{ key: 'person.name', validation: '', value: '' }]
*/
export function getKeyErrorValues<T extends Record<string, any>>(obj: T): PublicErrors {
export function getKeyErrorValues<T extends Record<string, any>>(
obj: T,
keysUpToValue: Array<string> = []
): PublicErrors {
let map = [];

for (let key in obj) {
errorKeysUpToValue.push(key);

if (obj[key] && isObject(obj[key])) {
if (
Object.prototype.hasOwnProperty.call(obj[key], 'value') &&
(obj[key] as any) instanceof Err
) {
map.push({
key: errorKeysUpToValue.join('.'),
key: [...keysUpToValue, key].join('.'),
validation: obj[key].validation,
value: obj[key].value
});
// stop collecting keys
errorKeysUpToValue = [];
} else if (key !== 'value') {
map.push(...getKeyErrorValues(obj[key]));
map.push(...getKeyErrorValues(obj[key], [...keysUpToValue, key]));
}
}
}

// reset
errorKeysUpToValue = [];

return map;
}
32 changes: 31 additions & 1 deletion test/utils/get-key-values.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getKeyValues } from '../../src/utils/get-key-values';
import { getKeyValues, getKeyErrorValues } from '../../src/utils/get-key-values';
import Err from '../../src/-private/err';

describe('Unit | Utility | getKeyValues', function() {
it('it works with single level values', () => {
Expand Down Expand Up @@ -27,3 +28,32 @@ describe('Unit | Utility | getKeyValues', function() {
]);
});
});

describe('Unit | Utility | getKeyErrorValues', function() {
it('it works with single level values', () => {
const result = getKeyErrorValues({
test: new Err(1, 'foobar')
});

expect(result).toEqual([{ key: 'test', value: 1, validation: 'foobar' }]);
});

it('it works with nested keys', () => {
const result = getKeyErrorValues({
user: {
firstName: new Err('Michael', 'Jordan'),
lastName: { value: 'Bolton' },
address: {
city: new Err('NYC', 'dungeon'),
state: new Err('New York', 'grassland')
}
}
});

expect(result).toEqual([
{ key: 'user.firstName', value: 'Michael', validation: 'Jordan' },
{ key: 'user.address.city', value: 'NYC', validation: 'dungeon' },
{ key: 'user.address.state', value: 'New York', validation: 'grassland' }
]);
});
});

0 comments on commit ce85db1

Please sign in to comment.