From dc8b25b803941aed3958631392bdb8eeac3eebd3 Mon Sep 17 00:00:00 2001 From: Avior Date: Thu, 6 Jun 2024 17:14:37 +0200 Subject: [PATCH] fix(object-util): objectGet with an empty path throwing the incorrect error Signed-off-by: Avior --- packages/object-util/__tests__/index.test.ts | 9 +++++++++ packages/object-util/src/ObjectUtil.ts | 6 +++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/object-util/__tests__/index.test.ts b/packages/object-util/__tests__/index.test.ts index d9309d4..a1a01c6 100644 --- a/packages/object-util/__tests__/index.test.ts +++ b/packages/object-util/__tests__/index.test.ts @@ -509,4 +509,13 @@ describe('object get', () => { expect(objectGet({a: { b: [{ c: 'pouet' }]}}, 'a.c.0')) .toEqual(undefined) }) + + it('object get should return undefined', () => { + expect(() => { + objectGet({a: { b: [{ c: 'pouet' }]}}, []) + }).toThrow() + expect(() => { + objectGet({a: { b: [{ c: 'pouet' }]}}, '') + }).toThrow() + }) }) diff --git a/packages/object-util/src/ObjectUtil.ts b/packages/object-util/src/ObjectUtil.ts index a172c95..201511b 100644 --- a/packages/object-util/src/ObjectUtil.ts +++ b/packages/object-util/src/ObjectUtil.ts @@ -350,6 +350,10 @@ export function objectFind export function objectGet(obj: object, path: Array | string): T | undefined { mustBeObject(obj) + if (path === '' || Array.isArray(path) && path.length === 0) { + throw new Error(`Path MUST at least have a value (${path})`) + } + // transform path into an Array if (typeof path === 'string') { path = path.split('.').map((it) => /^\d+$/g.test(it) ? Number.parseInt(it) : it) @@ -377,7 +381,7 @@ export function objectGet(obj: object, path: Array