Skip to content

Commit

Permalink
feat(ext/fetch): allow Deno.HttpClient to be declared with using (d…
Browse files Browse the repository at this point in the history
…enoland#21453)

This commit adds a method of `Symbol.dispose` to the object returned
from `Deno.createHttpClient`, so we can make use of [explicit resource
management](https://github.com/tc39/proposal-explicit-resource-management)
by declaring it with `using`.
  • Loading branch information
magurotuna committed Dec 6, 2023
1 parent 65993e5 commit dadd8b3
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
27 changes: 27 additions & 0 deletions cli/tests/unit/fetch_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1618,6 +1618,33 @@ Deno.test(
},
);

Deno.test(
{ permissions: { net: true } },
async function createHttpClientExplicitResourceManagement() {
using client = Deno.createHttpClient({});
const response = await fetch("http:https://localhost:4545/assets/fixture.json", {
client,
});
const json = await response.json();
assertEquals(json.name, "deno");
},
);

Deno.test(
{ permissions: { net: true } },
async function createHttpClientExplicitResourceManagementDoubleClose() {
using client = Deno.createHttpClient({});
const response = await fetch("http:https://localhost:4545/assets/fixture.json", {
client,
});
const json = await response.json();
assertEquals(json.name, "deno");
// Close the client even though we declared it with `using` to confirm that
// the cleanup done as per `Symbol.dispose` will not throw any errors.
client.close();
},
);

Deno.test({ permissions: { read: false } }, async function fetchFilePerm() {
await assertRejects(async () => {
await fetch(import.meta.resolve("../testdata/subdir/json_1.json"));
Expand Down
2 changes: 1 addition & 1 deletion cli/tsc/dts/lib.deno.unstable.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -847,7 +847,7 @@ declare namespace Deno {
*
* @category Fetch API
*/
export interface HttpClient {
export interface HttpClient extends Disposable {
/** The resource ID associated with the client. */
rid: number;
/** Close the HTTP client. */
Expand Down
6 changes: 6 additions & 0 deletions ext/fetch/22_http_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

const core = globalThis.Deno.core;
const ops = core.ops;
import { SymbolDispose } from "ext:deno_web/00_infra.js";

/**
* @param {Deno.CreateHttpClientOptions} options
Expand All @@ -33,9 +34,14 @@ class HttpClient {
constructor(rid) {
this.rid = rid;
}

close() {
core.close(this.rid);
}

[SymbolDispose]() {
core.tryClose(this.rid);
}
}
const HttpClientPrototype = HttpClient.prototype;

Expand Down

0 comments on commit dadd8b3

Please sign in to comment.