From 779200f5fc146f413efc14487be85cba63ddeb94 Mon Sep 17 00:00:00 2001 From: sabhas Date: Fri, 3 Sep 2021 13:54:02 +0500 Subject: [PATCH] fix: throw error if null or undefined is passed to getValidJson --- src/test/utils/getValidJson.spec.ts | 14 ++++++++++++++ src/utils/getValidJson.ts | 2 ++ 2 files changed, 16 insertions(+) diff --git a/src/test/utils/getValidJson.spec.ts b/src/test/utils/getValidJson.spec.ts index a84eb04..1e1f922 100644 --- a/src/test/utils/getValidJson.spec.ts +++ b/src/test/utils/getValidJson.spec.ts @@ -33,4 +33,18 @@ describe('jsonValidator', () => { } expect(test).toThrow(JsonParseArrayError) }) + + it('should throw an error when null is passed', () => { + const test = () => { + getValidJson(null as any) + } + expect(test).toThrow(InvalidJsonError) + }) + + it('should throw an error when undefined is passed', () => { + const test = () => { + getValidJson(undefined as any) + } + expect(test).toThrow(InvalidJsonError) + }) }) diff --git a/src/utils/getValidJson.ts b/src/utils/getValidJson.ts index 17f9cbb..8d8670b 100644 --- a/src/utils/getValidJson.ts +++ b/src/utils/getValidJson.ts @@ -6,6 +6,8 @@ import { JsonParseArrayError, InvalidJsonError } from '../types/errors' */ export const getValidJson = (str: string | object) => { try { + if (str === null || str === undefined) throw new InvalidJsonError() + if (Array.isArray(str)) throw new JsonParseArrayError() if (typeof str === 'object') return str