diff --git a/src/utils.ts b/src/utils.ts index c9f8dcd..96838f5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -54,19 +54,25 @@ export function setValue (obj: Record, path: string, val: any) { const keys = path.split('.') const _key = keys.pop() for (const key of keys) { + if (!obj || typeof obj !== 'object') { + return + } if (!(key in obj)) { obj[key] = {} } obj = obj[key] } if (_key) { + if (!obj || typeof obj !== 'object') { + return + } obj[_key] = val } } export function getValue (obj: Record, path: string) { for (const key of path.split('.')) { - if (!(key in obj)) { + if (!obj || typeof obj !== 'object' || !(key in obj)) { return undefined } obj = obj[key] diff --git a/test/utils.test.ts b/test/utils.test.ts new file mode 100644 index 0000000..1f688aa --- /dev/null +++ b/test/utils.test.ts @@ -0,0 +1,21 @@ +import { describe, it, expect } from 'vitest' +import { getValue, setValue } from '../src/utils' + +describe('getValue', () => { + it('handles inaccessible properties', () => { + const fixture = { top: false, test: { other: false, thing: { value: 'foo' } } } + expect(getValue(fixture, 'test.thing.value')).toBe('foo') + expect(getValue(fixture, 'test.other.value')).toBe(undefined) + expect(getValue(fixture, 'top.other.value')).toBe(undefined) + }) +}) + +describe('setValue', () => { + it('handles inaccessible properties', () => { + const fixture = { test: { other: false, thing: { value: 'foo' } } } + setValue(fixture, 'test.thing.value', 'bar') + expect(fixture.test.thing.value).toBe('bar') + setValue(fixture, 'test.other.value', 'ab') + expect(fixture.test.other).toBe(false) + }) +})