diff --git a/js/fetch.ts b/js/fetch.ts index d66eb1c48e..0a5f793a88 100644 --- a/js/fetch.ts +++ b/js/fetch.ts @@ -35,7 +35,7 @@ function hasHeaderValueOf(s: string, value: string): boolean { } class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser { - bodyUsed = false; + private _bodyUsed = false; private _bodyPromise: null | Promise = null; private _data: ArrayBuffer | null = null; readonly locked: boolean = false; // TODO @@ -223,6 +223,7 @@ class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser { } read(p: Uint8Array): Promise { + this._bodyUsed = true; return read(this.rid, p); } @@ -245,6 +246,10 @@ class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser { [Symbol.asyncIterator](): AsyncIterableIterator { return io.toAsyncIterator(this); } + + get bodyUsed(): boolean { + return this._bodyUsed; + } } export class Response implements domTypes.Response { @@ -252,7 +257,6 @@ export class Response implements domTypes.Response { readonly redirected: boolean; headers: domTypes.Headers; readonly trailer: Promise; - bodyUsed = false; readonly body: Body; constructor( @@ -302,6 +306,10 @@ export class Response implements domTypes.Response { return 200 <= this.status && this.status < 300; } + get bodyUsed(): boolean { + return this.body.bodyUsed; + } + clone(): domTypes.Response { if (this.bodyUsed) { throw new TypeError( diff --git a/js/fetch_test.ts b/js/fetch_test.ts index 8d8b581d8c..083d5333c3 100644 --- a/js/fetch_test.ts +++ b/js/fetch_test.ts @@ -1,5 +1,11 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -import { test, testPerm, assert, assertEquals } from "./test_util.ts"; +import { + test, + testPerm, + assert, + assertEquals, + assertThrows +} from "./test_util.ts"; testPerm({ net: true }, async function fetchJsonSuccess(): Promise { const response = await fetch("http://localhost:4545/package.json"); @@ -38,6 +44,19 @@ testPerm({ net: true }, async function fetchBlob(): Promise { assertEquals(blob.size, Number(headers.get("Content-Length"))); }); +testPerm({ net: true }, async function fetchBodyUsed(): Promise { + const response = await fetch("http://localhost:4545/package.json"); + assertEquals(response.bodyUsed, false); + assertThrows( + (): void => { + // Assigning to read-only property throws in the strict mode. + response.bodyUsed = true; + } + ); + await response.blob(); + assertEquals(response.bodyUsed, true); +}); + testPerm({ net: true }, async function fetchAsyncIterator(): Promise { const response = await fetch("http://localhost:4545/package.json"); const headers = response.headers; diff --git a/js/test_util.ts b/js/test_util.ts index bcbacf2812..52e09301b4 100644 --- a/js/test_util.ts +++ b/js/test_util.ts @@ -14,6 +14,7 @@ import { } from "./deps/https/deno.land/std/testing/asserts.ts"; export { assert, + assertThrows, assertEquals, assertMatch, assertNotEquals,