Readme
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { API_URL } from "https://esm.town/v/std/API_URL";
/**
* Wraps the JavaScript Fetch function to anonymize where the request is
* coming from ([Docs ↗](https://docs.val.town/std/fetch))
*
* @param {string | URL | Request} input - The resource to fetch.
* @param {RequestInit} [requestInit] - Optional configuration data (HTTP
* method, headers, etc) ([Docs ↗](https://deno.land/api@v1.42.1?s=RequestInit))
*/
export async function fetch(input: string | URL | Request, requestInit?: RequestInit) {
const origReq = new Request(input, requestInit);
const url = new URL("/v1/fetch", API_URL);
url.searchParams.set("url", origReq.url);
const req = new Request(url, origReq);
req.headers.set("X-Valtown-Authorization", `Bearer ${Deno.env.get("valtown")}`);
return globalThis.fetch(req);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
2
andreterron avatar

I merged your changes into my val and created a PR into @std/fetch :)

vladimyr avatar

@andreterron Thank you for reviewing and merging it but unfortunately, I made an error in the implementation.

https://www.val.town/v/andreterron/fetch_docs?v=9#L12-14 effectively means that requestInit will be discarded if the input is an instance of Request and that doesn't sound right. It prompted me to look elsewhere and see how different fetch implementations/polyfills deal with input + init combo and here's what I found. Basically, the first order of business if you are wrapping (native) fetch is to take both input and requestInit and produce origReq:

const origReq = new Request(input, requestInit);

It can be observed inside:

That's what happens when I'm trying to be too smart instead of opting for the simplest solution 😅

PR with the fix is on the way 🛫

April 4, 2024