From 0bc69401e5a2e3b4015058b64cbcf60e30dbde73 Mon Sep 17 00:00:00 2001 From: sabhas Date: Wed, 18 Aug 2021 00:02:48 +0500 Subject: [PATCH] chore: refactor code for getValidJson function --- src/test/utils/getValidJson.spec.ts | 15 +++++---------- src/utils/getValidJson.ts | 11 +++++++---- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/test/utils/getValidJson.spec.ts b/src/test/utils/getValidJson.spec.ts index e7fbf66..a84eb04 100644 --- a/src/test/utils/getValidJson.spec.ts +++ b/src/test/utils/getValidJson.spec.ts @@ -1,4 +1,5 @@ import { getValidJson } from '../../utils' +import { JsonParseArrayError, InvalidJsonError } from '../../types/errors' describe('jsonValidator', () => { it('should not throw an error with a valid json', () => { @@ -19,23 +20,17 @@ describe('jsonValidator', () => { it('should throw an error with an invalid json', () => { const json = `{\"test\":\"test\"\"test2\":\"test\"}` - let errorThrown = false - try { + const test = () => { getValidJson(json) - } catch (error) { - errorThrown = true } - expect(errorThrown).toBe(true) + expect(test).toThrowError(InvalidJsonError) }) it('should throw an error when an array is passed', () => { const array = ['hello', 'world'] - let errorThrown = false - try { + const test = () => { getValidJson(array) - } catch (error) { - errorThrown = true } - expect(errorThrown).toBe(true) + expect(test).toThrow(JsonParseArrayError) }) }) diff --git a/src/utils/getValidJson.ts b/src/utils/getValidJson.ts index 0313157..565ee98 100644 --- a/src/utils/getValidJson.ts +++ b/src/utils/getValidJson.ts @@ -1,16 +1,19 @@ +import { JsonParseArrayError, InvalidJsonError } from '../types/errors' + /** * if string passed then parse the string to json else if throw error for all other types unless it is not a valid json object. * @param str - string to check. */ export const getValidJson = (str: string | object) => { try { - if (Array.isArray(str)) { - throw new Error('Can not parse array object to json.') - } + const arrayErrorMessage = 'Can not parse array object to json.' + if (Array.isArray(str)) throw new JsonParseArrayError(arrayErrorMessage) + if (typeof str === 'object') return str return JSON.parse(str) } catch (e) { - throw new Error('Invalid JSON response.') + if (e instanceof JsonParseArrayError) throw e + throw new InvalidJsonError() } }