Skip to content

Commit

Permalink
Stop jhr XHR function from swallowing JSON.parse error
Browse files Browse the repository at this point in the history
Signed-off-by: Silas Davis <[email protected]>
  • Loading branch information
Silas Davis committed May 30, 2019
1 parent ef4f465 commit 2bbbd7f
Show file tree
Hide file tree
Showing 4 changed files with 1,327 additions and 857 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
lib/*
dist
.idea
17 changes: 14 additions & 3 deletions src/verbs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { StringMap } from "./types";
import { KeratinError } from "./types";
import {StringMap} from "./types";
import {KeratinError} from "./types";
import formData from "./formData";

export function get<T>(url: string, data: StringMap): Promise<T> {
Expand Down Expand Up @@ -33,7 +33,7 @@ function jhr<T>(sender: (xhr: XMLHttpRequest) => void): Promise<T> {
xhr.withCredentials = true; // enable authentication server cookies
xhr.onreadystatechange = () => {
if (xhr.readyState == XMLHttpRequest.DONE) {
const data: {result?: T, errors?: KeratinError[]} = (xhr.responseText.length > 1) ? JSON.parse(xhr.responseText) : {};
const data = maybeParseJSON<T>(xhr.responseText);

if (data.result) {
fulfill(data.result);
Expand All @@ -52,3 +52,14 @@ function jhr<T>(sender: (xhr: XMLHttpRequest) => void): Promise<T> {
sender(xhr);
});
}

function maybeParseJSON<T>(response: string): { result?: T, errors?: KeratinError[] } {
if (response === '') {
return {}
}
try {
return JSON.parse(response)
} catch (err) {
return {errors: [{message: `HTTP response '${response}' is not JSON as expected: ${err}`}]}
}
}
15 changes: 15 additions & 0 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,21 @@ QUnit.test("failure", function(assert) {
});
});

QUnit.test("Non JSON XHR response", function(assert) {
this.server.respondWith('POST', 'https://authn.example.com/session',
'Origin is not a trusted host.'
);

const expectedError = "HTTP response 'Origin is not a trusted host.' is not JSON as expected: SyntaxError: " +
"JSON.parse: unexpected character at line 1 column 1 of the JSON data"

return KeratinAuthN.login({username: 'test', password: 'test'})
.then(refuteSuccess(assert))
.catch(function(errors) {
assert.deepEqual(errors, [{message: expectedError}]);
});
});

QUnit.module("requestPasswordReset", startServer);
QUnit.test("success or failure", function(assert) {
this.server.respondWith('GET', 'https://authn.example.com/password/reset?username=test', '');
Expand Down
Loading

0 comments on commit 2bbbd7f

Please sign in to comment.