1
0
mirror of https://github.com/sasjs/adapter.git synced 2026-01-06 20:10:05 +00:00

chore: refactor code for getValidJson function

This commit is contained in:
2021-08-18 00:02:48 +05:00
parent 47fe7686cb
commit 0bc69401e5
2 changed files with 12 additions and 14 deletions

View File

@@ -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()
}
}