Skip to content

Commit 9cdd6e6

Browse files
committed
presumably showing that SimpleJSON can handle bad responses
1 parent e05fad4 commit 9cdd6e6

2 files changed

Lines changed: 25 additions & 7 deletions

File tree

src/JSON/Util.js

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
"use strict";
22

3+
let unsafeIsOk = function (val) {
4+
return !( typeof val === 'undefined' || val === null );
5+
}
6+
37
exports.tryPrettyJson = function (jString) {
48
var jsPretty = jString;
59
return function() {
@@ -17,11 +21,16 @@ exports.tryPrettyJson = function (jString) {
1721

1822
exports.preParse = function (jString) {
1923
var jsObj = JSON.parse(jString)
20-
jsObj['data']['attributes']['xml'] = undefined;
21-
var strOut = JSON.stringify(jsObj);
22-
if (strOut === undefined || strOut === null) {
23-
return "";
24-
} else {
25-
return strOut
26-
}
24+
if (unsafeIsOk(jsObj.data)
25+
&& unsafeIsOk(jsObj.data.attributes)
26+
&& unsafeIsOk(jsObj.data.attributes.xml)
27+
) {
28+
jsObj['data']['attributes']['xml'] = undefined;
29+
var strOut = JSON.stringify(jsObj);
30+
if (strOut === undefined || strOut === null) {
31+
return "";
32+
} else {
33+
return strOut
34+
}
35+
};
2736
};

test/Main.purs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,17 @@ main = do
4242
log $ show $ jsonFiles
4343
runTest do
4444
suite "JSON functions" do
45+
test "Can handle bad affjax response" testBadResponse
4546
test "Basic JSON success" $ traverse_ testJsonFile jsonFiles
4647

48+
testBadResponse :: Test
49+
testBadResponse = do
50+
let jsonResW = readRecordJSON respBody
51+
let (Tuple jsonRes errs) = runWriter $ unwrap jsonResW
52+
logNonFatals "NonFatal errors in parsing bad response" errs
53+
assert "not isLeft on bad response" $ isLeft jsonRes
54+
where
55+
respBody = "{\"errors\":[{\"status\":\"404\",\"title\":\"The resource you are looking for doesn't exist.\"}]}"
4756

4857
-- | Basic tests to see if parsing didn't fantastically fail.
4958
testJsonFile :: FilePath -> Test

0 commit comments

Comments
 (0)