Skip to content

Commit

Permalink
fix(xmlhttprequest): throw exception when invalid state (#123)
Browse files Browse the repository at this point in the history
  • Loading branch information
ykzts committed Jul 30, 2020
1 parent df398cf commit f46cdc0
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 4 deletions.
37 changes: 34 additions & 3 deletions src/xmlhttprequest.ts
Expand Up @@ -147,7 +147,11 @@ export default class XMLHttpRequest extends XMLHttpRequestEventTarget {
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
get response(): any {
get response(): ArrayBufferLike | Buffer | string | any | null {
if (this.readyState !== XMLHttpRequest.DONE) {
return null;
}

switch (this.responseType) {
case 'arraybuffer':
return new Uint8Array(this.#responseBuffer).buffer;
Expand All @@ -156,14 +160,32 @@ export default class XMLHttpRequest extends XMLHttpRequestEventTarget {
case 'document':
return this.responseXML;
case 'json':
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return JSON.parse(this.responseText);
try {
const text = this.#responseBuffer.toString();

// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return JSON.parse(text);
} catch {
return null;
}
default:
return this.responseText;
}
}

get responseText(): string {
if (this.responseType !== '' && this.responseType !== 'text') {
// TODO: Add human readable message.
throw new DOMException('', 'InvalidStateError');
}

if (
this.readyState !== XMLHttpRequest.LOADING &&
this.readyState !== XMLHttpRequest.DONE
) {
return '';
}

return this.#responseBuffer.toString();
}

Expand All @@ -190,6 +212,15 @@ export default class XMLHttpRequest extends XMLHttpRequestEventTarget {
}

get responseXML(): null {
if (this.responseType !== '' && this.responseType !== 'document') {
// TODO: Add human readable message.
throw new DOMException('', 'InvalidStateError');
}

if (this.readyState !== XMLHttpRequest.DONE) {
return null;
}

return null;
}

Expand Down
19 changes: 18 additions & 1 deletion test/integration/xmlhttprequest.ts
Expand Up @@ -241,7 +241,7 @@ describe('XMLHttpRequest', () => {
});
});

describe('.responseText', () => {
describe('.response', () => {
it('returns object when given JSON', (done) => {
const client = new XMLHttpRequest();

Expand All @@ -261,6 +261,23 @@ describe('XMLHttpRequest', () => {
client.responseType = 'json';
client.send(null);
});

it('returns null when given invalid JSON', (done) => {
const client = new XMLHttpRequest();

client.addEventListener('load', () => {
expect(client.response).toBe(null);

done();
});

client.open(
'GET',
`${baseURL}/?body=%7B%22test%22%3A%22value%22&type=application/json`
);
client.responseType = 'json';
client.send(null);
});
});

describe('.withCredentials', () => {
Expand Down

0 comments on commit f46cdc0

Please sign in to comment.