1
0
mirror of https://github.com/sasjs/adapter.git synced 2026-01-03 18:50:05 +00:00

Merge pull request #462 from sasjs/json-fix

fix: invalid json checking
This commit is contained in:
Allan Bowe
2021-07-14 20:46:16 +03:00
committed by GitHub
4 changed files with 77 additions and 14737 deletions

14773
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -429,8 +429,8 @@ export class RequestClient implements HttpClient {
throw new Error('Valid JSON could not be extracted from response.')
}
isValidJson(weboutResponse)
parsedResponse = JSON.parse(weboutResponse)
const jsonResponse = isValidJson(weboutResponse)
parsedResponse = jsonResponse
} catch {
parsedResponse = response.data
}

View File

@@ -0,0 +1,31 @@
import { isValidJson } from '../../utils'
describe('jsonValidator', () => {
it('should not throw an error with an valid json', () => {
const json = {
test: 'test'
}
expect(isValidJson(json)).toBe(json)
})
it('should not throw an error with an valid json string', () => {
const json = {
test: 'test'
}
expect(isValidJson(JSON.stringify(json))).toStrictEqual(json)
})
it('should throw an error with an invalid json', () => {
const json = `{\"test\":\"test\"\"test2\":\"test\"}`
expect(() => {
try {
isValidJson(json)
} catch (err) {
throw new Error()
}
}).toThrowError
})
})

View File

@@ -2,9 +2,11 @@
* Checks if string is in valid JSON format else throw error.
* @param str - string to check.
*/
export const isValidJson = (str: string) => {
export const isValidJson = (str: string | object) => {
try {
JSON.parse(str)
if (typeof str === 'object') return str
return JSON.parse(str)
} catch (e) {
throw new Error('Invalid JSON response.')
}